1

以下 MATLAB 代码不起作用。我想它在函数转换器中有一些事情要做,MATLAB 尝试使对象相等,AB不仅仅是将值设置为相同。有什么解决方法吗?

classdef foo
    %FOO Summary of this class goes here
    %   Detailed explanation goes here

    properties
        A=5
        B=0
    end

    methods
        function changer(obj)
            obj.B=obj.A
        end
    end

end
4

1 回答 1

5

I think the code is actually working fine, just not doing quite what you expect.

The way you've defined it, foo is a value class, so it has value semantics, rather than reference (or handle) semantics. When you execute changer(myobj), MATLAB is creating a copy of myobj with the new value of B and returning it to you. The original myobj remains unchanged. When implementing a value class, you would typically add an output argument to changer in order to be able to further work with this new copy.

function obj = changer(obj)

If you set foo to be a handle class, by inheriting from handle:

classdef foo<handle

it will then have reference (or handle) semantics, where the original myobj is modified (you then no longer need the output argument from changer):

>> myobj = foo;
>> changer(myobj); % or alternatively myobj.changer
>> myobj.B
ans =
     5
于 2011-11-29T17:29:56.643 回答