属性在面向对象的 MATLAB 中如何工作?
我正在尝试创建一个 MATLAB 类,其中的成员变量由于方法调用而更新,但是当我尝试更改类中的属性时,它(显然,根据我对 MATLAB 内存管理的理解)会创建一个副本对象的属性,然后修改它,保持原始对象的属性不变。
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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用值(普通)类
当使用值类时,您需要告诉 Matlab 存储对象的修改副本以保存属性值中的更改。 因此,
正如 Kamran 指出的那样,这需要更改函数
的定义请求
使用句柄类
如果您继承自句柄类,那么
您可以编写,
请注意,这会更改对象的行为,请参阅文档 了解值类和句柄类之间的区别。
Using a Value (Vanilla) Class
When using a value class you need to tell Matlab to store a modified copy of the object to save the changes in the property value. So,
As Kamran notes, this requires changing the definition of function
Request
to beUsing a Handle Class
If you inherit from the handle class, that is
then you can write,
Note that this changes the behavior of the objects, see the documentation to learn the difference between a value class and a handle class.
您必须记住,在 Matlab 中的语法上,您可能更接近于 C,而不是 C++ 或 Java,至少在对象方面是这样。 因此,如果您想要更改值对象(实际上只是一个特殊的
struct
)的“内容”,您需要从函数返回该对象。Azim 正确地指出,如果您想要 Singleton 行为(从您的代码中,您可以似乎),你需要使用“句柄”类。 从 Handle 派生的类的实例都指向单个实例,并且仅对其进行操作。
您可以阅读有关 Value 和 Value 之间差异的更多信息处理类。
You have to remember that syntactically in Matlab, you're probably closer to C, than C++ or Java, at least with respect to objects. So, of you want to change the "contents" of a value object (really just a special
struct
), you need to return the object from the function.Azim was correct to point out that if you want Singleton behavior (which, from your code, you seem to), you need to use a "handle" class. Instances of classes that derive from Handle all point to a single instance, and operate only on it.
You can read more about the differences between Value and Handle classes.
我创建了类 testprop 并尝试执行 Azim 建议的代码,但它不起作用。 当我执行以下命令时:
生成以下错误:
我认为问题在于我们在声明 Request 方法时没有确定任何输出。 所以我们应该将其更改为:
现在:
I made the class testprop and tried to excute the code which Azim suggested but it did not work. When I executed the following command:
The following error was generated:
I think the problem is that we did not determine any output when declaring Request method. So we should change it to:
and now: