How to pass a class name as argument to a function
조회 수: 33 (최근 30일)
표시 이전 댓글
Hello,
I'd like to initialize an element of a class with another class instance, and I'd like to pass in the particular class as an object. For example:
classdef Aclass < handle
properties
thingObj
end
methods
function this = Aclass(thingClassName)
this.thingObj = thingClassName(arg1,arg2,etc);
end
end
end
This code doesn't work, though ("Index exceeds matrix dimensions"). I assume the problem is you can't call the () operator on an existing object.
Instead, I do this, which does work, but isn't pretty:
classdef SomeClass < handle
properties
thingObj
end
methods
function this = SomeClass(thingClassName)
this.thingObj = eval([class(thingClassName) '(arg1,arg2,etc)']);
end
end
end
There's no checking in the string argument list, and errors in this line are hard to debug.
I could instantiate the object outside the constructor, but that's problematic. I'd like to instantiate the object within the "SomeClass" constructor because it knows the right way to do it.
I'm guessing this is really simple and that I haven't stumbled on the right way yet. Any ideas?
Thanks,
Charles
댓글 수: 0
채택된 답변
Jeff Miller
2019년 1월 30일
I think the first classdef ("Aclass") works fine, as long as you pass to its constructor the handle of the class you want instantiated. So, for example,
myobj = Aclass(@theClassToInstantiate)
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Software Development Tools에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!