属性如何在面向对象的 MATLAB 中工作? [英] How do properties work in Object Oriented MATLAB?

查看:20
本文介绍了属性如何在面向对象的 MATLAB 中工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个 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  

推荐答案

使用 Vanilla 类

当使用 vanilla 类时,您需要告诉 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

更新:使用 Vanilla 类

正如 Kamran 指出的上述内容的定义<问题示例代码中的 code>Request 方法需要更改为包含 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆