MATLAB 面向对象编程 Cheatsheet

A Simple Class

Doc Link

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
classdef BasicClass
properties % 属性
Value
end
methods
function obj = BasicClass(val) % 构造函数
if nargin == 1
if isnumeric(val)
obj.Value = val;
else
error('Value must be numeric')
end
end
end
function r = roundOff(obj) % 普通成员函数
r = round([obj.Value],2);
end
function r = multiplyBy(obj,n)
r = [obj.Value] * n;
end
function r = plus(o1,o2) % 操作符重载
r = [o1.Value] + [o2.Value];
end
end
end

% Some basic operations
a.Value
a.Value = pi/3;
a = BasicClass;
a = BasicClass(pi/3);
multiplyBy(a, 3)
a.multiply(3)
roundOff([BasicClass(2.7984), BasicClass(7)])
a + b % call plus(o1,o2)

Class Components

Doc Link

Class Definition Block

1
2
3
classdef (Sealed) MyClass < handle
...
end

Properties Block

1
2
3
4
5
6
classdef MyClass
properties (Access = private)
Prop1 = date();
end
...
end

Methods Block

1
2
3
4
5
6
7
classdef MyClass
methods (Access = private)
function obj = myMethod(obj)
...
end
end
end

Events Block

1
2
3
4
5
6
classdef EventSource
events (ListenAccess = protected)
StateChanged
end
...
end

Enumeration Block

1
2
3
4
5
6
classdef Boolean < logical
enumeration
No (0)
Yes (1)
end
end