我创建了一个类xyz
,它产生的矩阵只包含整数。如果我尝试添加该类的两个实例,我会收到错误消息:
“未定义的运算符'+'表示'xyz'类型的输入参数。”
我应该做些什么来使内置+
运算符与我的类的实例兼容?
答案 0 :(得分:6)
您必须使用plus
method to override the behavior of +
classdef MyObject
properties
value
end
methods
function this = MyObject(v)
this.value = v;
end
function result = plus(this, that)
% Create a new object by adding the value property of the two objects
result = MyObject(this.value + that.value);
end
end
end
然后使用它:
one = MyObject(1)
% MyObject with properties:
%
% value: 1
two = MyObject(2)
% MyObject with properties:
%
% value: 2
three = one + two
% MyObject with properties:
%
% value: 3
对于其他常见运营商,有一个广泛的列表here