필터 지우기
필터 지우기

constructor called twice when creating array of object. why?

조회 수: 4 (최근 30일)
Christof
Christof 2012년 6월 20일
This is sort of a double post, as it is an issue I ran into when following a solution to a previous problem. So, sorry for that, but this really confuses me. As an example, I have a class
classdef someClass
properties
name
value
end
methods
function obj = someClass(name)
if ~nargin
% the default constructor. Needed for array creation
obj.name = '';
else
% only take care of the array part for simplicity:
if iscell(name)
[obj(1:length(name)).name] = deal(name{:});
end
end
display('object created')
end
end
end
When I run c=someClass({'a' 'b' 'c' 'd' 'e'}) I get the output object created object created
c =
1x5 someClass
Properties:
name
value
Methods
So, the constructor seems to be called twice. The second time, it is called w/o input arguments. So if I comment the blocks that checks for number of input arguments to be >0, I get the result Error using someClass (line 13) Not enough input arguments.
Error in someClass (line 14) [obj(1:length(name)).name] = deal(name{:});
when I run c=someClass({'a' 'b' 'c' 'd' 'e'}). Why does it run the constructor twice? How can I avoid that.
Thanks for any help, Chris

답변 (1개)

Daniel Shub
Daniel Shub 2012년 6월 20일
The documentation says that "During the creation of object arrays, MATLAB might need to call the class constructor with no arguments ..." While you might be able to avoid it, I don't think it is a good idea.

카테고리

Help CenterFile Exchange에서 Properties에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by