Why do I have to create empty object array before calling constructor in constructor?

5 次查看(过去 30 天)
If I call constructor in the workspace using MATLAB's cheap copies, I get an object array that is exactly what MATLAB's help documentation says. Ex. #1
>> obj(3) = myClass(1,2);a = [obj.a],b = [obj.b]
a =
2 2 1
b =
4 4 2
But if I put the same commands in the constructor, I get an object array that is nearly the same, except that the first element now only has the defaults from my properties block. Ex. #2
>> obj = myClass(1,2,3);a = [obj.a],b = [obj.b]
a =
999 2 1
b =
999 4 2
Unless I create an empty object array first. Ex. #3
>> obj = myClass(1,2,3);a = [obj.a],b = [obj.b]
a =
2 2 1
b =
4 4 2
The examples above use the following m-file:
classdef myClass < handle
properties
a = 999
b = 999
end
methods
function obj = myClass(a,b,c)
if nargin<3
c = 1;
end
if c>1
% uncomment for Ex. #3
% obj = myClass.empty(0, c);
obj(c) = myClass(a,b);
else
if nargin<1
a = 2;
end
obj.a = a;
if nargin<2
b = 4;
end
obj.b = b;
end
end
end
end

采纳的回答

Mark Mikofski
Mark Mikofski 2011-8-3
When the constructor is called, it instantiates the object with any defaults given in the properties block ([] for any properties without defaults), so in my example above, a scalar object was already instantiated.
If c>2 the call
obj(c) = myClass(a,b);
requires MATLAB to fill in
obj(2:c-1)
with cheap copies (created by calling the constructor without arguments). Calling the empty method replaces the object with an empty array, so the call
obj(c) = myClass(a,b);
now acts as expected.
Another option would be to delete the default object before expanding it.
obj.delete
BTW: MATLAB states that an object is destroyed if its variable is assigned to a new value or when the function ends, so you do not need to free memory. http://www.mathworks.com/help/techdoc/matlab_oop/brfylzt-1.html#bsxw4_c
  1 个评论
Mark Mikofski
Mark Mikofski 2015-5-14
here's another example of this behavior with doubles:
>> clear
>> x= 1.23 # <1x1 double>
x =
1.23
>> x(10) = 5 # grow x to <1x10 double>
x =
1.23 0 0 0 0 0 0 0 0 5.00
>> y(10) = 5 # create <1x10 double>
y =
0 0 0 0 0 0 0 0 0 5

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Software Development Tools 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by