【发布时间】:2013-11-22 21:42:20
【问题描述】:
例如,假设我创建了一个名为Shape 的抽象类和两个名为Circle 和Rectangle 的子类,它们都实现了一个名为Draw 的(抽象)方法。我希望能够创建多个 Circle 和 Rectangle 对象,将它们存储在一个数组中,并通过遍历数组对每个数组对象调用 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
test.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();
【问题讨论】:
标签: matlab oop polymorphism matlab-class