assign class object to array

5 visualizaciones (últimos 30 días)
Markus Leuthold
Markus Leuthold el 7 de Ag. de 2019
Respondida: Steven Lord el 7 de Ag. de 2019
Assume the following class
classdef A < handle
methods
function obj = A
disp('constructor called')
end
end
end
Now create an array of 10 instances of A
>> a(10) = A
constructor called
constructor called
Why is the constructor called twice? Why not 10x or 1x?

Respuesta aceptada

Steven Lord
Steven Lord el 7 de Ag. de 2019
You've told MATLAB that you want fill element 10 of the array a with the output returned by a call to the constructor with no inputs. MATLAB also needs to know what you want elements 1 through 9 to be and it determines the latter by making a call to the constructor with no inputs, as stated on this documentation page. It uses that "default" element of the class (from the automatic 0-input constructor call) to fill in all the elements up to element 10, then uses the one you explicitly created as that tenth element.
Actually, checking back I see your object is a handle object. In that case, see this other documentation page which goes into a bit more detail about how that is handled. Same general answer, but with an extra detail or two specific to handle objects.

Más respuestas (0)

Categorías

Más información sobre Construct and Work with Object Arrays en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by