属性如何在面向对象的MATLAB中工作? [英] How do properties work in Object Oriented MATLAB?
问题描述
我正在尝试创建一个成员类,该成员类由于方法调用而被更新,但是当我尝试更改该类中的属性时(从我对MATLAB内存管理的理解来看)创建对象的副本,然后对其进行修改,而保持原始对象的属性不变.
I am trying to create a MATLAB class with a member variable that's being updated as a result of a method invocation, but when I try to change the property within the class it (apperently, from what I understood from MATLAB's memory management) creates a copy of the object and then modifies it, leaving the original object's property untouched.
classdef testprop
properties
numRequests=0;
end
methods
function Request(this, val)
disp(val);
this.numRequests=this.numRequests+1;
end
end
end
.
>> a=testprop;
>> a.Request(9);
>> a.Request(5);
>> a.numRequests
ans = 0
推荐答案
使用香草类
使用香草类时,您需要告诉Matlab存储对象的修改后的副本,以将更改保存到属性值中.所以,
Using a Vanilla Class
When using vanilla class you need to tell Matlab to store a modified copy of the object to save the changes in the property value. So,
>> a=testprop
>> a.Request(5); % will NOT change the value of a.numRequests.
5
>> a.Request(5)
5
>> a.numRequests
ans =
0
>> a=a.Request; % However, this will work but as you it makes a copy of variable, a.
5
>> a=a.Request;
5
>> a.numRequests
ans =
2
使用句柄类
如果您从handle类继承,那就是
Using the Handle Class
If you inherit from the handle class, that is
classdef testprop < handle
然后您就可以写
>> a.Request(5);
>> a.Request(5);
>> a.numRequests
ans =
2
更新:使用香草类
作为 Kamran 的注释,上述内容可用于<问题的示例代码中的c0>方法需要更改,以包含类型为 testprop 的输出参数.
Update: Using Vanilla Class
As Kamran notes for the above to work the definition of the Request
method in the question's example code needs to be changed to include an output argument of type testprop.
感谢卡姆兰.
这篇关于属性如何在面向对象的MATLAB中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!