【发布时间】:2016-07-06 20:48:18
【问题描述】:
我能否创建对句柄对象的引用,以便在某一点替换对象本身并更新引用?
例子:
classdef IShifter < handle
methods (Abstract)
x = Shift(this, x);
end
end
classdef Shifter1 < IShifter
methods
function x = Shift(this, x)
x = circshift(x, 1);
end
end
end
classdef Shifter2 < IShifter
methods
function x = Shift(this, x)
x = [ 0 ; x ];
end
end
end
classdef Item
properties (Access = 'private')
shifter; % should be a pointer/reference to the object which is in the respective parent container object
end
methods
function this = Item(shifter)
this.shifter = shifter;
end
function x = test(this, x)
x = this.shifter.Shift(x);
end
end
end
% note this is a value class, NOT a handle class!
classdef ItemContainer
properties
shifter;
items;
end
methods
function this = ItemContainer()
this.shifter = Shifter1;
this.items{1} = Item(this.shifter);
this.items{2} = Item(this.shifter);
end
function Test(this)
this.items{1}.Test( [ 1 2 3] )
this.items{2}.Test( [ 1 2 3] )
end
end
end
那么,输出应该是:
items = ItemContainer();
items.Test();
[ 3 1 2 ]
[ 3 1 2 ]
items.shifter = Shifter2;
items.Test();
[ 0 1 2 ]
[ 0 1 2 ]
但实际上是:
items = ItemContainer();
items.Test();
[ 3 1 2 ]
[ 3 1 2 ]
items.shifter = Shifter2;
items.Test();
[ 3 1 2 ]
[ 3 1 2 ]
因为将新的 Shifter 对象分配给父对象项不会更新容器中的引用。
我正在寻找类似 C 中的所有“移位器”属性都是指针的东西,我可以将任何我想要的移位器对象放入这个“地址”。
ItemContainer 和 Item 不是句柄类。 我想避免使用事件来更新引用或实现 set 方法来更新引用
【问题讨论】:
标签: matlab pointers reference pass-by-reference