Is there inheritable behavior (or a Mixin) for setting/getting the 'Parent' and 'Children' properties of a custom class?
3 ビュー (過去 30 日間)
古いコメントを表示
I ran into a problem with setting the Parent and Children of a user-defined class, and I ended up writing my own methods that seem a lot more complicated than they need to be. I'm wondering if there is inheritable behavior for this?
classdef superClass
properties
Parent = [];
Children = [];
end
methods
function obj = superClass( varargin )
% Set the parent, children given input.
p = inputParser;
addOptional( p, 'Parent', obj.Parent );
addOptional( p, 'Children', obj.Children );
parse( p, varargin{:} );
obj.setParent( p.Results.Parent );
obj.setChildren( p.Results.Children );
end
function setParent( obj, otherObj )
% Behaviour of this function should probably be a lot more nuanced than this:
obj.Parent = otherObj;
end
function setChildren( obj, otherObj )
% Probably don't want to have multiple references to the same Child?
obj.Children = vertcat( otherObj, obj.Children );
end
end
end
classdef subClass < superClass
properties
end
methods
function obj = subClass( varargin )
p = inputParser;
addOptional( p, 'Parent', obj.Parent );
addOptional( p, 'Children', obj.Children );
parse( p, varargin{:} );
% Set myClass instance's Parent, Children given input AND concurrently
% set superClass' instance's Children to include this new subClass object.
obj.setParent( p.Results.Parent ); % This needs to be overridden?
obj.setChildren( p.Results.Children ); % This needs to be overridden?
end
end
end
I want these classes to be able to make the following code error-free:
dad = superClass();
son = subClass( 'Parent', dad );
if ismember( dad, son.Parent )
disp( 'hooray' )
else
disp( 'booooo' )
end
2 件のコメント
per isakson
2019 年 12 月 6 日
I would have expected
ismember( dad, son.Parent )
rather than
ismember( dad.Children, son.Parent )
採用された回答
per isakson
2019 年 12 月 6 日
編集済み: per isakson
2019 年 12 月 6 日
"make the following code error-free"
There is a problem regarding handle or value class. In the code it's assumed that superClass is a handle-class, however it's defined as a value-class. I assume you intended it as a handle-class and replace
classdef superClass
by
classdef superClass < handle
Furthermore, I replace subClass by
classdef subClass < superClass
properties
end
methods
function obj = subClass( varargin )
obj@superClass( varargin{:} );
end
end
end
(propably not needed)
Now
%%
dad = superClass();
son = subClass( 'Parent', dad );
%%
if ismember( dad, son.Parent )
disp( 'hooray' )
else
disp( 'booooo' )
end
prints hooray in the Command Window
"there is inheritable behavior for this?" AFAIK: No
0 件のコメント
その他の回答 (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!