Matlab 多态性

标签 matlab oop polymorphism matlab-class

我有两个新式 MATLAB 类 - BC,它们都是抽象父类 A 的具体子类。 Ahgsetset(句柄类)的子类。我想将它们放在 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/

相关文章:

performance - 高效计算光流参数 - MATLAB

r - 无法将矩阵数类强制为整数

image - 如何改变RGB图像的动态范围?

java - 如何比较 Java 中属性中也包含列表的两个对象

c# - 用任何设计模式或更好的方法替换 if else 语句

c++ - C2440 static_cast 无法从基类转换为派生类

c++ - 模板类中的循环依赖

java - Jackson 可以使用它没有编写的 boolean JSON 属性反序列化为具体子类吗?

Matlab滤波器的实现

python - 具有扭曲色彩图的 3D 绘图