问题
I am trying to used updatable object (class) in Matlab with nested class. I observe a behavior that seems to be due to the handle status.
I write the 2 classes testA and testB. testB is a the main class that calls the class testA as a property:
classdef testB
properties
objA=testA;
end
methods
function obj=testB()
obj.objA
if isempty(obj.objA.val)
obj.objA.val=5;
else
obj.objA.val=obj.objA.val+5;
end
end
function up(obj)
obj.objA.val=obj.objA.val+6;
obj.objA.val
end
end
end
Firstly, testA is a handle class.
classdef testA < handle
properties
val=[];
end
methods
function obj=testA()
end
function set.val(obj,tt)
obj.val=tt;
end
end
end
When I create testB object two times
tt=testB
tt=testB
I observe that the val property in testA is not reinitialized (val in testA keeps the previous value). I am not sure but it seems to be due to the handle feature. The method tt.up increase the val property in testA as expected.
Secondly if I change the testA class to a value class.
classdef testA
properties
val=[];
end
methods
function obj=testA()
end
function obj=set.val(obj,tt)
obj.val=tt;
end
end
end
In this case the successive calls of tt=testB create each time a new instance of testB with a new instance of testA. Unfortunately in this case the up methods does not work as expected (the new computed value of val is not stored in the object).
A solution could be to consider handle class for testA and force to delete it before fully initialize the testB object. However I don't know how to do this.
回答1:
This is documented behavior: in your testB definition, obj=testA is evaluated only once, when the class definition is loaded. All instances of the class will have a reference to the same handle class object.
Just below on same documentation page you'll see that you should create a new instance of testA in the constructor for testB, if you want a different instance of testA for each instance of testB:
classdef testB
properties
objA
end
methods
function obj=testB()
objA = testA;
% ... further initialization
end
end
end
来源:https://stackoverflow.com/questions/58169408/nested-classdef-with-or-without-handle