constructor called twice when creating array of object. why?

4 次查看(过去 30 天)
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