有或没有句柄的嵌套classdef? [英] Nested classdef with or without handle?
问题描述
我正在尝试使用Matlab中的可更新对象(类)和嵌套类.我观察到似乎是由于手柄状态引起的行为.
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.
我写了两个类testA
和testB
. testB
是将类testA
作为属性调用的主要类:
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
首先,testA
是一个句柄类.
classdef testA < handle
properties
val=[];
end
methods
function obj=testA()
end
function set.val(obj,tt)
obj.val=tt;
end
end
end
当我两次创建testB
对象时
tt=testB
tt=testB
我发现testA
中的val
属性没有重新初始化(testA
中的val
保留了以前的值).我不确定,但这似乎是由于handle
功能所致.方法tt.up
按预期增加testA
中的val
属性.
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.
第二,如果我将testA
类更改为值类.
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
在这种情况下,每次testB
的新实例和testA
的新实例时,都会连续创建tt=testB
的调用.不幸的是,在这种情况下,up
方法无法按预期方式工作(val
的新计算值未存储在对象中).
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).
一种解决方案是在完全初始化testB
对象之前,考虑为testA
使用handle
类,并强制将其删除.但是我不知道该怎么做.
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.
推荐答案
这是已记录的行为:在您的testB
定义中,obj=testA
仅在加载类定义时被评估一次.该类的所有实例都将引用相同的句柄类对象.
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.
只需在同一文档页面上,您将会看到,如果您要为每个testB
实例使用不同的testA
实例,则应该在testB
的构造函数中创建testA
的新实例:
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
这篇关于有或没有句柄的嵌套classdef?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!