classdef MyClassName
% 添加属性
properties
prop1
prop2 = datestr(now); % prop2的默认值
end
% 添加方法
methods
% constructor:方便创建类里的对象
function obj = MyClassName(val1, val2)
if nargin == 2
obj.prop1 = val1;
obj.prop2 = val2;
end
end
function outarg = ordMethods(obj, arg1)
outrag = obj.x + obj.y + arg1
end
% overloading
function objout = plus(obj1, obj2)
objout = MyClassName;
objout.prop1 = obj.prop1 + obj.prop2
end
function objout = minus(obj1, obj2)
objout = MyClassName;
objout.prop1 = obj.prop1 + obj.prop2
end
end
end
1.创建空白对象(类方法中没有constrcutor)
MCN1 = MyClassName
MCN2 = MyClassName
2.修改对象的属性(类方法中没有constrcutor)
MCN1.prop1 = 3
MCN1.prop2 = 4
3.创建对象,如果类方法中有constrcutor,一定要给属性赋值,否则报错
MCN1 = MyClassName(3,4)
MCN2 = MyClassName(5,6)
4.使用可变输入变量nargin,可避免3不给属性赋值的错误
5.如果在properties对属性进行了赋值,没有新输入则为默认值
MCN1 = MyClassName
MCN2 = MyClassName
MCN1==MCN2
6.MCN1和MCN2相同,并且clear之后再次运行仍然相同,但是clear all可彻底清楚内存中的记忆
classdef SimpleClass
properties
x
y = 33;
end
methods
function obj = SimpleClass(val1, val2)
if nargin == 0
obj.x = 0
elseif nargin == 1
obj.x = 1
else
obj.x = varargin{1};
obj.y = varargin{2};
end
end
function outarg = ordMethods(obj, arg1)
outrag = obj.x + obj.y + arg1
end
end
end
7.properties函数获得对象的属性,methods函数获得对象的方法
newobject = SimpleClass(4, 22)
properties(newobject)
methods(newobject)
8.测试不同的输入
newobject = SimpleClass
newobject = SimpleClass(56)
newobject = SimpleClass(33, 45, 698, 623)
9.使用类方法的几种方式
ordMethod(newobject, 1)
newobject.ordMethod(1)
overloading
classdef Rectangle
properties
len = 0;
width = 0;
end
methods
function obj = Rectangle(l,w)
if nargin == 2
obj.len = l;
obj.width = w;
end
end
function outarg = rectarea(obj)
outarg = obj.len*obj.width;
end
function out = lt(obj1, obj2)
out = lt(rectarea(obj1), rectarea(obj2));
end
function out = gt(obj1, obj2)
if isa(obj2, 'Rectangle')
out = gt(rectarea(obj1), rectarea(obj2));
else
% 1.out = gt(rectarea(obj1), 20);
inp2 = Rectangle(obj2, 1);
out = get(obj1, inp2);
end
function disp(obj)
fprintf('The rectangle has length %.2f and withd %.2f. \n', obj.len, obj. width)
end
end
end