在对象的构造函数中传递对象
Pass object in the constructor of an object
假设我有一个 class
classdef Dummy
properties
property % to be assigned with an object
end
methods
function obj = Dummy(in)
% Constructor. Assign this object to `in.property`
if nargin > 0
in.property = obj;
end
end
end
end
我想要的是通过执行代码
z = Dummy();
z1 = Dummy(z);
我将 z.property = z1
z
的 property
分配给对象 z1
但实际上,当我执行上面的代码片段时,z.property = []
总是空的。如何实现我想要的行为(最好使用构造函数)?
我尝试调试它,发现即使使用 in.property = obj;
语句也一切正常。问题出现在走出对象时,where z.property=[]
again.
问题通过指定handle
超类
解决
classdef Dummy < handle
properties
property % to be assigned with an object
end
methods
function obj = Dummy(in)
% Constructor. Assign this object to `in.property`
if nargin > 0
in.property = obj;
end
end
end
end
这样创建对象作为引用。否则,此 in.property = obj
将尝试提供对象的副本,从而导致失败。
假设我有一个 class
classdef Dummy
properties
property % to be assigned with an object
end
methods
function obj = Dummy(in)
% Constructor. Assign this object to `in.property`
if nargin > 0
in.property = obj;
end
end
end
end
我想要的是通过执行代码
z = Dummy();
z1 = Dummy(z);
我将 z.property = z1
z
的 property
分配给对象 z1
但实际上,当我执行上面的代码片段时,z.property = []
总是空的。如何实现我想要的行为(最好使用构造函数)?
我尝试调试它,发现即使使用 in.property = obj;
语句也一切正常。问题出现在走出对象时,where z.property=[]
again.
问题通过指定handle
超类
classdef Dummy < handle
properties
property % to be assigned with an object
end
methods
function obj = Dummy(in)
% Constructor. Assign this object to `in.property`
if nargin > 0
in.property = obj;
end
end
end
end
这样创建对象作为引用。否则,此 in.property = obj
将尝试提供对象的副本,从而导致失败。