How to inherite and intialize object values

1 回表示 (過去 30 日間)
parmeshwar prasad
parmeshwar prasad 2019 年 6 月 10 日
編集済み: per isakson 2019 年 6 月 11 日
classdef inputDef
properties
nMatch
end
methods
function obj = inputDef(varargin)
p = inputParser;
p.addParameter('nMatch', 1, @isnumeric);
p.parse(varargin{:});
obj.nMatch = p.Results.nMatch; % Position of the sorting parameters
end
end
end
I have a superclass inputDef which has propety nMatch. I create an object and assign a value as below
>>in = inputDef
>>in.nMatch = 2
How do I inherit inputDef in a another class such that I can get
>> out = outDef(in)
>> out.nMatch = 2
classdef outDef < inputDef
properties
...
end
methods
function obj = outDef(obj1)
obj = obj1
end
end
end
Please give some idea. Thanks in advance

採用された回答

Matt J
Matt J 2019 年 6 月 10 日
編集済み: Matt J 2019 年 6 月 10 日
What you've shown would work, but you have to actually assign the properties,
function obj = outDef(obj1)
obj.nMatch = obj1.nMatch;
obj.prop1=_____
obj.prop2=_____
etc...
end

その他の回答 (1 件)

per isakson
per isakson 2019 年 6 月 10 日
編集済み: per isakson 2019 年 6 月 11 日
"How do I inherit inputDef in a another class such that [...]"
%%
in = inputDef();
in.nMatch = 2;
%%
out = outDef( in );
%%
out.val.nMatch
outputs
ans =
2
where
classdef inputDef
properties
nMatch = 0;
end
methods
function obj = inputDef(varargin)
p = inputParser;
p.addParameter('nMatch', 1, @isnumeric);
p.parse(varargin{:});
obj.nMatch = p.Results.nMatch; % Position of the sorting parameters
end
end
end
and
classdef outDef
properties
val
end
methods
function this = outDef( obj )
this.val = obj;
end
end
end
That's the standard way, however, to get a bit closer to your proposed code
classdef outDef < inputDef
properties
end
methods
function this = outDef( obj )
this.nMatch = obj.nMatch;
end
end
end
but that looks weird to me. Anyhow, out.nMatch, returns 2
>> out.nMatch
ans =
2
>>

カテゴリ

Help Center および File ExchangeConstruct 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