mercredi 23 septembre 2015

References to elements in vectors during construction

In C++, I have a class MyClass, which during construction takes a reference to an int to create an internal reference to it.

I then have a class BigClass, containing both an std::vector<int> vecInt_ and an std::vector<MyClass> vecMyClass_. The constructor of BigClass takes as an argument the size of the vectors vecInt_ and vecMyClass_. In the constructor of BigClass, I would like to have each element of vecMyClass_ use in its constructor the corresponding element of vecInt_.

How could I write that ? If I could call the constructors of vecMyClass from the body of the constructor of BigClass, that would look like that :

BigClass(int nbElem) :
    vecInt_(nbElem),
    vecMyClass_(nbElem)
{
    for (int i = 0; i < nbElem; ++i)
    {
        vecMyClass_[i](vecMyInt_[i]);
    }
}

But of course the parenthesis here would mean operator(), and not the constructor. I cannot write something like:

vecMyClass_[i] = MyClass(vecMyInt_[i]);

Because MyClass contains a reference and not a pointer, and thus referenced value can not be modified.

Aucun commentaire:

Enregistrer un commentaire