Domanda

Mi chiedo perché ho bisogno di dichiarare un costruttore predefinito in questo caso.Per una cosa non il compilatore non lo fa automaticamente se la lascio fuori?E a prescindere, non capisco ancora perché è necessario.Inoltre, ottengo l'errore anche se ometto 'obj_b= origin.obj_b;'

class B
{
public:
    bool theArray[5] ;

    B(bool x) {theArray[1] = x;};
    //B(){};    
};

class A
{
public:
    B obj_B;

    A() : obj_B(1) {};
    A(A const &origin) {obj_B = origin.obj_B;}; //error:no matching function for call 
                                                      //to B::B()
}; 

int main () 
{
    std::vector <A> someAs;
    for(int q=0;q<10;q++)
        someAs.push_back(A());

    for(int q=0;q<10;q++)
        std::cout << someAs[q].obj_B.theArray[1] << std::endl;
}
.

È stato utile?

Soluzione

The compiler only creates a default constructor if you don't specify an alternate constructor.

Because you made:

B(bool x) {theArray[1] = x;}

The default constructor will not be created for you.

The specific error you're getting is because A(A const &origin) doesn't specify the constructor to use for obj_B explicitly.

The following code would work:

A(A const &origin) : obj_B(1) {obj_B = origin.obj_B;}

By the way, you don't need a trailing semicolon on a function definition.

Altri suggerimenti

If you don't define any ctors for a class, the compiler will synthesize a default constructor. If you define another constructor though (e.g., one that takes an argument) then the compiler does not synthesize one for you, and you have to define one yourself.

In case you care, C++ 0x adds an "=default;" declaration to tell the compiler to provide a ctor that it would have provided by default, even if you have defined another ctor.

To define a copy constructor for A that does not require a default constructor for B, use member initializer syntax:

class A {
public:
    A(A const& origin) : obj_B(origin.obj_B) {}
    //...
};

To make one final point...

Assuming you hadn't defined a non-default constructor, failing to define a default constructor would've resulted in the elements of theArray[] being undefined. That is a bad habit to get into usually leading to bugs down the road.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top