gpt4 book ai didi

matlab - 如何在 MATLAB 中创建抽象类对象数组?

转载 作者:行者123 更新时间:2023-12-02 06:54:07 24 4
gpt4 key购买 nike

举个例子,假设我创建了一个名为 Shape 的抽象类和两个名为 CircleRectangle 的子类,它们都实现了 (abstract ) 调用 Draw 的方法。我希望能够创建许多 CircleRectangle 对象,将它们存储在数组中,并通过以下方式在每个数组对象上调用 Draw遍历数组。

我尝试过类似以下的方法:

形状.m:

classdef (Abstract) Shape < handle

methods (Abstract)
Draw(obj);
end

end

圆.m:

classdef Circle < Shape

methods
function obj = Draw(obj)
disp('This is a circle');
end
end

end

矩形.m:

classdef Rectangle < Shape

methods
function obj = Draw(obj)
disp('This is a rectangle');
end
end

end

测试.m:

shapes = Shape.empty();

myrect = Rectangle();
mycirc = Circle();

shapes(end + 1) = myrect;
shapes(end + 1) = mycirc;

for i = 1:size(shapes,1)
shapes(i).Draw();
end

当我尝试运行 test.m 时,收到以下错误消息:

Error using Shape.empty
Abstract classes cannot be instantiated.
Class 'Shape' defines abstract methods
and/or properties.

Error in test (line 1)
shapes = Shape.empty();

最佳答案

从错误中可以清楚地看出,you cannot instantiate an abstract class (有关详细信息,请参阅塞巴斯蒂安的回答)。然而,有一个特殊的父类(super class)称为 matlab.mixin.Heterogeneous您可以从中派生以允许创建不同类的数组。

首先,从 Shape.m 中的 matlab.mixin.Heterogeneous 派生:

classdef (Abstract) Shape < handle & matlab.mixin.Heterogeneous

然后在您的测试脚本中,从 CircleRectangle 初始化 shapes:

shapes = Circle.empty();

当您运行循环时,数组将更改类:

>> shapes

shapes =

1x2 heterogeneous Shape (Rectangle, Circle) array with no properties.

>> shapes(1)

ans =

Rectangle with no properties.

>> shapes(2)

ans =

Circle with no properties.

这应该就是您所需要的,但为了对异构阵列进行额外控制,您可以覆盖 the getDefaultScalarElement method matlab.mixin.Heterogeneous 来指定默认对象。这应该被抽象基类覆盖:

Override this method if the Root Class is abstract or is not an appropriate default object for the classes in the heterogeneous hierarchy. getDefaultScalarElement must return an instance of another member of the heterogeneous hierarchy.

假设您希望派生自 Shape 的对象数组的默认对象为 Circle:

methods (Static, Sealed, Access = protected)
function default_object = getDefaultScalarElement
default_object = Circle;
end
end

现在,从 Shape 派生的对象数组中缺少的元素将由 Circle 对象填充:

>> clear r
>> r(2) = Rectangle
r =
1x2 heterogeneous Shape (Circle, Rectangle) array with no properties.
>> r(1)
ans =
Circle with no properties.
>> r(2)
ans =
Rectangle with no properties.

关于matlab - 如何在 MATLAB 中创建抽象类对象数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36180346/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com