Why do I have to create empty object array before calling constructor in constructor?
Afficher commentaires plus anciens
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
Réponse acceptée
Plus de réponses (0)
Catégories
En savoir plus sur Class Introspection and Metadata dans Centre d'aide et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!