简体   繁体   中英

Composition of classes

How come, when setting up class composition, contained classes can be called with a default constructor but not with one that takes parameters?

That's kind of confusing; let me offer an example.

#include "A.h"
class B
{
private:
    A legal; // this kind of composition is allowed
    A illegal(2,2); // this kind is not.
};

Assuming both the default constructor and one that takes 2 integers exists, only one of these is allowed. Why is this?

It is allowed for sure, but you just need to write it differently. You need to use the initializer list for the composite class's constructor:

#include "A.h"

class B
{
private:
    A legal; // this kind of composition is allowed
    A illegal; // this kind is, too
public:
    B();
};

B::B() :
    legal(), // optional, because this is the default
    illegal(2, 2) // now legal
{
}

You can provide constructor parameters, but you are initialising your members wrong.

#include "A.h"

class B
{
private:
    int x = 3; // you can't do this, either
    A a(2,2);
};

Here's your solution, the ctor-initializer :

#include "A.h"

class B
{
public:
    B() : x(3), a(2,2) {};
private:
    int x;
    A a;
};

a class declaration does NOT initialize the members which compose the class. hence, the error when you are trying to constrcut an object inside the declaration.

member initialization takes place inside the constructor of a class. so you should write:

#include "A.h"
class B
{
public:
    B();
private:
    A a;
};

B::B() : 
    a(2,2)
{
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM