daleonpz daleonpz - 3 months ago 14
C++ Question

error 2d vector class initialization in class

I defined the class

Brique
. The constructor accepts a
forme
and
couleur
as follows:

class Brique
{
private:
Forme forme ;
Couleur couleur ;

public:
Brique(Forme _forme, Couleur _couleur)
:forme(_forme), couleur(_couleur) {}
};


I have defined a new class called
Construction
which constructor should use a class
Brique
to initialize a vector of 1x1. But when I compiled I got this error :


error: no matching function for call to
‘std::vector::vector(Brique&)’

:contenu(1,vector(brique)){}


Code of class
Construction
:

class Construction
{
private:
vector<vector<Brique> > contenu;

public:
Construction(Brique& brique)
:contenu(1,vector<Brique>(brique)){}

};


here is the main

int main()
{
Brique test("square", "red");
Construction temp(test);
return 0;
}


I know how to initialize vector using pointers like this:

vec.push_back(new Brique(test) )


but this creates a new instances and I want to use only references to my instance
test
.

Answer

In the class Construction you are initialising the field contenu incorrectly. You mention that you want to initialise it as a 1x1 std::vector in the constructor. To do this you must use constructor (2) referenced in the std::vector::vector documentation.

So, try the following instead:

class Construction {
private:
    std::vector<std::vector<Brique>> contenu;
public:
    Construction(const Brique& brique)
        : contenu(1, std::vector<Brique>(1, brique)) {}
};

That will set contenu to a 1x1 "matrix" containing the value of brique initially.

Comments