calling subclass method does not pass the obj only the argument

조회 수: 3 (최근 30일)
Micke Malmström
Micke Malmström 2017년 12월 13일
답변: Micke Malmström 2018년 4월 25일
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
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
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개)

Micke Malmström
Micke Malmström 2018년 4월 25일
This seems to work:
OBJ=FLUS;
OBJ.fun1(OBJ,extravalues);

카테고리

Help CenterFile 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!

Translated by