参加以下课程
classdef MyClass
properties (Access = public)
MyProperty;
end
methods
function this = MyClass()
% initialize the class
this.MyProperty = [];
this.LoadProperty(2,2);
end
function p = GetProperty(this)
p = this.MyProperty;
end
function this = LoadProperty(this, m, n)
% loads the property
this.MyProperty = zeros(m, n);
end
end
end
然后您致电:
obj = MyClass();
obj.GetProperty()
它将返回[]
-这是MyProperty
在构造方法中分配的第一个值。
该LoadProperty
方法充当设置器,但不设置任何内容。我如何为它创建一个二传手MyProperty
?我来自C#背景,那里很简单。->解决(见下文)
我怀疑这是引用和对象的问题,因为MATLAB始终将对象本身作为第一个参数发送给类的每个方法,而不是像C#那样仅发送引用。
先感谢您!
编辑:
如果我将行更改this.LoadProperty(2,2);
为this = this.LoadProperty(2,2);
,则可以。
现在,有没有一种方法可以在MATLAB中创建一个void返回方法,该方法仅设置类属性,就像通常在C#,C ++,Java等中所期望的那样?
由于已将其声明为公共,因此可以直接访问它:
classObj = MyClass;
classObj.MyProperty = 20;
classObj.MyProperty % ans = 20
但是似乎您想封装它。有几种方法可以做到这一点。假设您具有私有访问权限,如下所示。
classdef MyClass
properties (Access = private)
MyProperty;
end
methods
function this = MyClass()
% initialize the class
this.MyProperty = [];
this.LoadProperty(2,2);
end
function p = GetProperty(this)
p = this.MyProperty;
end
function this = LoadProperty(this, m, n)
% loads the property
this.MyProperty = zeros(m, n);
end
end
end
然后,可以向其添加set方法,如下所示(我通常对函数和变量使用小写字母,对类使用大写字母。可以根据需要将其更改为大写字母):
function this = setProperty(this,value)
this.MyProperty = value;
end
由于这不是句柄类,因此您将需要按以下方式使用此函数:
myClass = myClass.setProperty(30); % You can also set it to [30 30 30; 20 20 20] if you want, there are no restrictions if you don't explicitly write into your function.
否则,您可以通过以下方式使用句柄类:
classdef MyClass < handle
在这种情况下,您可以通过以下方法直接更改它:
myClass.setProperty(40);
但这也意味着您对此类的任何引用都不会创建新对象,而是该对象的另一个句柄。也就是说,如果您这样做:
myClass2 = myClass;
% and uses myClass2.setProperty:
myClass2.setProperty(40)
myClass.GetProperty % ans = 40!
因此,如果您想避免这种行为(也就是说,当您将类传递给一个函数或另一个变量(也就是按值调用)时想要一个类的副本),但想指定应如何获取和设置方法行为上,Matlab提供了两个内置方法,您可以在分配属性时重载它们。那是:
function out = get.MyProperty(this)
function set.MyProperty(this,value)
通过覆盖这些方法,您将覆盖用户调用时发生的情况
myClass.MyProperty % calls out = get.MyPropertyGet(this)
myClass.MyProperty = value; % calls set.MyProperty(this,value)
但是您也可以使用句柄类并为您的类创建一个复制函数:
function thisCopy = copy(this)
nObj = numel(this);
thisCopy(nObj) = MyClass;
meta = metaclass(MyClass);
nProp = numel(meta,'PropertyList');
for k = 1:nObj
thisCopy(k) = MyClass; % Force object constructor call
for curPropIdx=1:nProp
curProp = meta.PropertyList(curPropIdx);
if curProp.Dependent
continue;
end
propName = curProp.Name;
thisCopy(k).(propName) = this(k).(propName);
end
end
end
应该get.
set.
在classdef内部将其指定为(就像您的方法一样)作为公共方法。如果您声明了此方法,并希望将class2
其作为的副本class
,那么您会这样:
myClass = MyClass;
myClass.setProperty(30);
myClass2 = copy(myClass);
myClass2.setProperty(40); %
myClass.GetProperty % ans = 30
对于MyClass应该更复杂一点,因为它handle
从类对象中复制每个(非)属性,并在有类对象数组时工作。有关更多参考,请参见@Amro的答案和matlab oop文档。
这也是为什么this = this.LoadProperty
起作用和this.LoadProperty(2,2)
不起作用的解释。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句