Anyone know how to create a multidimensional subclass constructor?
2 次查看(过去 30 天)
显示 更早的评论
Hello!
My problem is, that I'm trying to write a subclass to my multidimensional superclass, but i run into errors trying to call the superclasses constructor in the subclass constructor.
The superclasses constructor looks somewhat like this:
function obj = A( arg1, arg2, arg3 )
if nargin == 0
return;
end
n = numel( arg1 );
obj( n , 1 ) = A();
for i=1:n
% some code
end
end
Now I would like to build a subclass to this one, with some additional parameters, but I have no idea about the syntax for the subclass. The syntax written in the Matlab Documentation doesn't help at all for this kinda multidimensional cases.
Thanks in advance!
0 个评论
采纳的回答
Guillaume
2016-10-13
That's a very interesting question and I think it shows another problem with matlab class design.
The problem you'll encounter when constructing a derived object (let's call it B) is that in the superclass constructor, obj is still of class B and thus the line obj(n, 1) = A is going to cause an error, since A can't be converted to B. In A constructor obj should never be of type B.
There is an ugly workaround, use eval to construct the array of the required type. You'll end up with:
classdef A
properties
a;
end
methods
function this = A(arg1, arg2, arg3)
if nargin == 0 %to support array construction
return;
else
this(numel(arg1), 1) = eval(class(this)); %use eval to invoke the correct constructor
arg1 = num2cell(arg1); [this.a] = arg1{:}; %distribute arg1 into each object
end
end
end
end
classdef B < A
properties
b;
end
methods
function this = B(Barg, arg1, arg2, arg3)
if nargin == 0 %can't call base constructor inside if, so build base constructor arguments
args = {};
else
args = {arg1, arg2, arg3};
end
this@A(args{:}); %and call base constructor
if nargin > 0
Barg = num2cell(Barg);
[this.b] = Barg{:};
end
end
end
end
I'm going to raise that as an issue with mathworks as this shows that there is no decent way of initialising an object array. Assigning to the last element of array is fragile and breaks under your circumstances. I really hate that constructing an object and an array of object is done in the same constructor.
2 个评论
Andrew Stamps
2023-11-7
This may only be my personal preference in avoiding eval wherever possible, but it could be replaced by str2fun as follows.
...
con = str2func(class(this));
this(numel(arg1), 1) = con(); %use str2func to invoke the correct constructor
...
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Construct and Work with Object Arrays 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!