我有两个新式 MATLAB 类 - B
和 C
,它们都是抽象父类 A
的具体子类。 A
是hgsetset
(句柄类)的子类。我想将它们放在 MATLAB 中的一个数组中,并将它们都视为 A
。它们大致定义为:
classdef A <hgsetget
methods
function foo(this)
%does some common stuff, then
this.fooWorker;
end
end %public Methods
methods(Abstract, Access=protected)
fooWorker(this);
end %abstract Methods;
end
classdef B < A
methods(Access=protected)
function fooWorker(this)
%implementation
end
end %protected Methods;
end
但是如果我这样做:
arr = [b c]; % where b & c are objects of type B & C respectively.
arr(1).foo;
arr(2).foo;
MATLAB 会告诉我两者都是 B
类型,如果我从 A
调用两者都实现 (foo
) 的抽象方法,本质上,它执行 b
的两个副本。
但是,如果我颠倒顺序:
arr = [c b];
它告诉我两者都是 C
类型,如果我尝试在两者上执行 foo,它就会执行,本质上是 c
的两个副本。
关于如何以多态方式使用子类有什么想法吗?
我知道我可以将它们放在一个元胞数组中并获得我需要的 90%。但这有点麻烦。
最佳答案
您现在可以通过子类化 matlab.mixin.Heterogeneous 在 R2011a 中执行此操作。因此,例如在您的代码中,抽象类将是:
classdef A < matlab.mixin.Heterogeneous
methods
function foo(this)
disp('In abstract parent');
this.fooWorker;
end
end
methods(Abstract, Access=protected)
fooWorker(this);
end
end
子类看起来像:
classdef B < A
methods(Access=protected)
function fooWorker(this)
disp('In B');
end
end
end
对于“C”类也是如此。然后从 MATLAB 得到以下输出:
>> b = B;
>> c = C;
>> arr = [b, c];
>> arr(1).foo
In abstract parent
In B
>> arr(2).foo
In abstract parent
In C
>>
关于Matlab 多态性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1458088/