【发布时间】:2012-01-25 10:18:29
【问题描述】:
我正在尝试在 Matlab 中使用单继承,并编写一个基类构造函数,该构造函数允许创建对象数组,包括空数组,并且由子类继承。如果不使用一些非常笨拙的代码,我无法弄清楚如何做到这一点。一定有更好的办法。
在这个玩具示例中,我的基类称为 MyBaseClass,我的子类称为 MySubClass。每个都可以用单个数字参数构造,或者没有参数(在这种情况下假定为 NaN)。在玩具示例中,我的 SubClass 是微不足道的,不会以任何方式扩展 MyBaseClass 的行为,但显然在实践中它会做更多的事情。
我希望能够按如下方式调用每个的构造函数:
obj = MyBaseClass; % default constructor of 'NaN-like' object
obj = MyBaseClass([]); % create an empty 0x0 array of type MyBaseClass
obj = MyBaseClass(1); % create a 1x1 array of MyBaseClass with value 1
obj = MyBaseClass([1 2; 3 4]) % create a 2x2 array of MyBaseClass with values 1, 2, 3, 4.
同样的四个调用 MySubClass。
我找到的解决方案需要调用eval(class(obj)) 以恢复子类名称并在字符串中构造代码以在基类构造函数中调用。这看起来既笨拙又糟糕。 (这让我有点惊讶,但它是可能的。)我想我可以在MyBaseClass 和MySubClass 构造函数之间复制更多逻辑,但这似乎也很笨拙和糟糕,并且错过了继承的要点。有没有更好的办法?
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% MyBaseClass.m
classdef MyBaseClass
properties
data = NaN
end
methods
% constructor
function obj = MyBaseClass(varargin)
if nargin == 0
% Handle the no-argument case
return
end
arg = varargin{1};
% assume arg is a numeric array
if isempty(arg)
% Handle the case ClassName([])
% Can't write this, because of subclasses:
% obj = MyBaseClass.empty(size(arg));
obj = eval([class(obj) '.empty(size(arg))']);
return
end
% arg is an array
% Make obj an array of the correct size by allocating the nth
% element. Need to recurse for the no-argument case of the
% relevant class constructor, which might not be this one.
% Can't write this, because of subclasses
% obj(numel(arg)) = MyBaseClass;
obj(numel(arg)) = eval(class(obj));
% Rest of the constructor - obviously in this toy example,
% could be simplified.
wh = ~isnan(arg);
for i = find(wh(:))'
obj(i).data = arg(i);
end
% And reshape to the size of the original
obj = reshape(obj, size(arg));
end
end
end
% end of MyBaseClass.m
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% MySubClass.m
classdef MySubClass < MyBaseClass
methods
function obj = MySubClass(varargin)
obj = obj@MyBaseClass(varargin{:});
end
end
end
% end of MySubClass.m
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
【问题讨论】:
-
您是否尝试从构造函数内部调用被基类覆盖的函数(例如,在对象完成构造之前)?在大多数语言中,这是非法的。
标签: oop matlab inheritance constructor