OOP: Array object
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Hello everyone,
My question is :
i need an array of objects. That array should be able to perform methods like add, remove etc. .
i was thinking about writing a class which has the array as property. Something like this
classdef MyArray
properties
array
end
methods
.
.
.
end
end
But i noticed that its kind of annoying to always type obj.array to get access to the property.
So, is there any other way to implement an array? Something where an instance of the class itself is an array. Similiar to java.
Thanks in advance!
0 commentaires
Réponses (2)
Guillaume
le 5 Avr 2017
In matlab everything is an array, even classes you design yourself. If you come from other languages such as Java or C++ this is something that can be bit disconcerting. There is no difference between a scalar object and an array object. See for example:
classdef DemoClass
properties
value;
end
methods
function this = DemoClass() %constructor
this.value = randi(100);
end
function sz = howbigamI(this)
%the this object to any method can be an array
sz = size(this);
end
function showvalues(this)
for i = 1:numel(this)
fprintf('object(%d) has value:%d\n', i, this(i).value);
end
fprintf('\n');
end
end
end
>> o = DemoClass
o =
DemoClass with properties:
value: 27
>> o.howbigamI
ans =
1 1
>> o(5) = DemoClass
o =
1×5 DemoClass array with properties:
value
>> o.howbigamI
ans =
1 5
>> o.showvalues
object(1) has value:27
object(2) has value:21
object(3) has value:21
object(4) has value:21
object(5) has value:82
You actually have to go out of your way to prevent classes from being used as non-scalar.
2 commentaires
Guillaume
le 5 Avr 2017
You're still making the mistake of thinking in Java. In matlab, an array of edges and an edge are one and the same. A method of the array is a method of the edge.
So, if you want to have custom method for the edge array, you have to add the method to the edge class. That method will apply equally to scalar edge object and array of edge objects.
Voir également
Catégories
En savoir plus sur Argument Definitions dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!