matriz de objetos donde el constructor tiene un argumento

I want to have an array of objects. Each object has a constructor with one argument. My object array initialisation :

set s[]=new set[n]; // creates an array of n objects of class set

However, it says that I cannot do so, because my constructor requires an argument. My Constructor:

set(int size){}

I've understood the problem, but cant think of a good solution. What I can do, is either initialise each object seperately :

set s1(size);
set s2(size); //& so on.....

or remove the argument from constructor......both solutions are not quite satisfactory

Can anyone help me out to find a better solution to this ?

Note: 'size' value of each object is different/dynamic

preguntado el 22 de septiembre de 13 a las 17:09

2 Respuestas

#include <vector>
std::vector<set> s(n, set(x,y,z));

This will create a vector (a dynamically resizeable array) of n set objects, each a copy of set(x,y,z). If you want to use different constructors for various elements, or the same constructor with different arguments:

std::vector<set> s;      // create empty vector
... // repeat until s.size() == n

Respondido el 22 de Septiembre de 13 a las 17:09

You can make a different constructor that takes no arguments and initializes the values, and then set the values of each variable in a loop

set() {
    this.size = 0;

and then in a for loop initialize each element with the desired size, using direct binding or a getter/setter functions.

for(int i = 0; i < n; i++) {
    s[i].size = value[i]; // or create a setter function

Respondido el 22 de Septiembre de 13 a las 18:09

Yeah, I had the same thing in mind earlier, but I specifically wanted to initialise it using constructor. Thanks for the effort. - sumedh

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.