课程组成

hea*_*ter 4 c++

为什么在设置类组合时,可以使用默认构造函数调用包含的类,但不能使用带参数的类调用?

那有点令人困惑; 让我举一个例子.

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

假设存在默认构造函数和存在2个整数的构造函数,则只允许其中一个.为什么是这样?

Tho*_*mas 8

这是肯定的,但你只需要以不同的方式编写它.您需要为复合类的构造函数使用初始化列表:

#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
{
}
Run Code Online (Sandbox Code Playgroud)