为自己的类/对象重载Addition(+)运算符

And*_*ndi 3 oop matlab operator-overloading

我创建了一个类xyz,它产生一个只包含整数的矩阵.如果我尝试添加该类的两个实例,我收到错误消息:

"未定义的运算符'+'表示'xyz'类型的输入参数."

我应该做些什么来使内置+运算符与我的类的实例兼容?

Sue*_*ver 6

您必须使用该plus方法来覆盖行为+

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
Run Code Online (Sandbox Code Playgroud)

然后使用它像:

one = MyObject(1)
%  MyObject with properties:
%
%   value: 1


two = MyObject(2)
%  MyObject with properties:
%
%   value: 2

three = one + two
%  MyObject with properties:
%
%   value: 3
Run Code Online (Sandbox Code Playgroud)

对于其他常用的运营商,有一个详细的列表在这里