构造函数可以在c ++中调用另一个类的构造函数吗?

Sco*_*tie 4 c++ constructor

class A {
public:
    A(int v) {
        _val = v;
    }

private:
    int _val;
};

class B {
public:
    B(int v) {
        a = A(v); // i think this is the key point
    }

private:
    A a;
};

int main() {
    B b(10);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

编译说:

test.cpp: In constructor ‘B::B(int)’:
test.cpp:15: error: no matching function for call to ‘A::A()’
test.cpp:5: note: candidates are: A::A(int)
test.cpp:3: note:                 A::A(const A&)
Run Code Online (Sandbox Code Playgroud)

我已经学习了Java,我不知道如何在C++中处理这个问题.搜索了几天,PLZ告诉我C++可以这样做吗?

Alo*_*ave 15

您需要使用成员初始化列表

B(int v):a(v)
{
}
Run Code Online (Sandbox Code Playgroud)

附:

B(int v) 
{
        a = A(v); // i think this is the key point
}
Run Code Online (Sandbox Code Playgroud)

a正在分配一个值而不是被初始化(这是你想要的),一旦构造函数的主体开始{,它的所有成员都已构造.

为什么会出错?
编译器a在构造函数体{开始之前构造,编译器使用无参数构造函数,A因为你没有告诉它,否则注1,因为默认的没有参数构造函数不可用因此错误.

为什么不隐式生成默认的无参数构造函数?
一旦为类提供了任何构造函数,就不再生成隐式生成的无参数构造函数.您为构造函数提供了重载A,因此没有隐式生成无参数构造函数.

注1:
使用Member Initializer List是告诉编译器使用构造函数的特定重载版本而不是默认的无参数构造函数的方法.


mfo*_*ini 6

您必须使用初始化列表:

class B {
public:
    B(int v) : a(v) { // here

    }

private:
    A a;
};
Run Code Online (Sandbox Code Playgroud)

否则编译器将尝试A使用默认构造函数构造一个.由于您没有提供,因此会出现错误.