calling subclass method does not pass the obj only the argument

5 ビュー (過去 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 Center および File ExchangeWhos についてさらに検索

製品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by