classdef phase < handle
properties
nVars double ;
boundaries boundaries ;
end
methods
function obj = phase(nVars)
%Some constructor method
obj.nVars = nVars;
obj.boundaries = boundaries(obj);
end
end
end
classdef boundaries
properties
parent phase
upper double ;
lower double ;
end
methods
function obj = boundaries( parent )
% Assign the parent handle
obj.parent = parent ;
% Initialise default values for the properties
obj.upper = Inf * ones([1 parent.nVars]);
obj.lower = -obj.upper ;
end
end
end
此初始化正确:>> a = phase(5)
a =
phase with properties:
nVars: 5
boundaries: [1x1 boundaries]
>> a.boundaries
ans =
boundaries with properties:
parent: [1x1 phase]
upper: [Inf Inf Inf Inf Inf]
lower: [-Inf -Inf -Inf -Inf -Inf]
classdef语法允许在属性中方便地定义默认值,以限制必须在构造函数中完成的编码工作(自动检查输入类型和各种输入检查)。
但是,对于在属性块中定义的每个默认值,MATLAB都会在对象的构造函数中添加自动生成的代码。一旦最终创建并初始化了对象,如果直接在属性块或构造函数中分配了属性值,它将产生[无差异]。对于您的情况,要添加到构造函数中的代码非常琐碎,以至于不值得花很多时间来尝试找到可以在属性块中使用的语法。此外,在您的情况下,这总是会因为另一个问题而失败:通过引用传递。
[当您尝试为boundaries类中的父对象分配一个句柄时,您只是在发送初始阶段对象的
副本。该副本将位于boundaries对象中,但与实际的phase父对象没有关联。为了能够通过引用传递父对象,您需要将handle传递给该父对象,为此,您需要将父类定义为handle。