필터 지우기
필터 지우기

How can I create an inherit class based on variable value?

조회 수: 8 (최근 30일)
Chung-Tao Chou
Chung-Tao Chou 2023년 2월 20일
편집: chrisw23 2023년 2월 20일
Hi,
I've defined multiple classes (class1, class2, class3...) which all inherit from one class (class0):
classdef class0 ...
classdef class1 < class0 ...
classdef class2 < class0 ...
classdef class3 < class0 ...
and I have a variable 'index', which is 1 or 2 or 3. I'm trying to create a object whose class type is based on this index. For example, if index is 1, I want a object of class1. So far I can acheive this by calling a function like in the following code:
function test = create_class_obj(index)
switch index
case 1
test = class1();
case 2
test = class2();
case 3
test = class3();
end
end
Is there an elegant way to encode this into the constructor of class0? So that I can do the following:
test = class0(index);
Thanks.
Josh

채택된 답변

Steven Lord
Steven Lord 2023년 2월 20일
You could create a function handle to the constructor then call that function handle.
index = 2; % example
fh = str2func("class" + index)
fh = function_handle with value:
@class2
fh()
Inside class2
You'd probably want to check (either before creating the function handle or while calling it, using try and catch) that the class you're trying to instantiate exists.
But I would not put this into the constructor of class0. I would instead make a factory function or method that creates the appropriate subclass object.
function class0()
disp("Inside class0")
end
function class1()
disp("Inside class1")
end
function class2()
disp("Inside class2")
end
function class3()
disp("Inside class3")
end
  댓글 수: 1
Chung-Tao Chou
Chung-Tao Chou 2023년 2월 20일
Hi Steven,
Thanks for the prompt answer. To make sure I understand you, the factory function that you mentioned is like the function in my code:
function test = create_class_obj(index)
except I don't need to use switch-case, and I can use the handle method instead?
Best,
Josh

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

chrisw23
chrisw23 2023년 2월 20일
편집: chrisw23 2023년 2월 20일
classdef baseClass < handle
methods
function baseClass(index)
...
end
end
...
classdef class0 < baseClass
methods
function class0(index)
% explicitly call the superclass constructor with argument
@obj.baseClass(index)
end
...

카테고리

Help CenterFile Exchange에서 Class File Organization에 대해 자세히 알아보기

제품


릴리스

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by