calling subclass method does not pass the obj only the argument
3 次查看(过去 30 天)
显示 更早的评论
I have these classes
classdef LUS < handle
methods
function fun1(obj,extravalues)
%some code using extravalues
end
end
end
and:
classdef FLUS < LUS
methods
function fun1(obj,extravalues)
fun1@LUS(obj, extravalues);
%some extra code using extravalues
end
end
end
however when I run
OBJ=FLUS;
OBJ.fun1(extravalues);
then as "fun1" of "LUS" is executed nargin is only 1. Meaning that obj="extravalues" and extravalues is undefined...
How should I call fun1@LUS(obj, extravalues) so that "obj" is passed as "obj" and "extravalues" is passed as "extravalues"?
4 个评论
Steven Lord
2017-12-13
That's not the behavior I see in release R2017b. Here are my versions of your class definitions, with a few lines added to display some diagnostic information.
>> type LUS.m
classdef LUS < handle
methods
function fun1(obj,extravalues)
%some code using extravalues
disp('Inside fun1 in LUS')
whos
nargin
end
end
end
>> type FLUS.m
classdef FLUS < LUS
methods
function fun1(obj,extravalues)
disp('Inside fun1 in FLUS')
whos
nargin
fun1@LUS(obj, extravalues);
%some extra code using extravalues
end
end
end
Here's how I used those classes.
>> OBJ=FLUS;
>> extravalues = 1:10;
>> OBJ.fun1(extravalues);
Inside fun1 in FLUS
Name Size Bytes Class Attributes
extravalues 1x10 80 double
obj 1x1 8 FLUS
ans =
2
Inside fun1 in LUS
Name Size Bytes Class Attributes
extravalues 1x10 80 double
obj 1x1 8 FLUS
ans =
2
As you can see, the superclass method received both the inputs with which the subclass method called it. You didn't mention what you used for extravalues, so I chose a simple double array.
Adam
2017-12-13
编辑:Adam
2017-12-13
Personally, when doing this I favour the option of not over-riding the base class function and instead having a setup as:
classdef LUS < handle
methods
function fun1(obj,extravalues)
% Do some common base class stuff
doFun1( obj, extravalues )
end
end
methods( Access = protected )
function doFun1( obj, extravalues )
end
end
end
and in the subclass:
classdef FLUS < LUS
methods( Access = protected )
function doFun1(obj,extravalues)
%some extra code using extravalues
end
end
end
There are also variations on that that I use, depending if the subclass should always add something (in which case make the function abstract in the super class) or if it should be pre- or post- what the base class does.
It is mostly just a question of taste though. Your version should work from what I see.
回答(1 个)
另请参阅
类别
在 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!