[英]Can constructor call another class's constructor in c++?
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;
}
编译说:
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&)
我已经学习了Java,我不知道如何在C ++中处理这个问题。 搜索了几天,PLZ告诉我C ++可以这样做吗?
您需要使用成员初始化列表
B(int v):a(v)
{
}
附:
B(int v)
{
a = A(v); // i think this is the key point
}
a
被分配了一个值而没有被初始化 ( 这是你想要的 ),一旦构造函数的主体开始{
,它的所有成员都已经被构造。
为什么会出错?
编译器构造a
before构造函数体{
开始,编译器使用A
的无参数构造函数,因为你没有告诉它,否则注1 ,因为默认的无参数构造函数不可用因此错误。
为什么不隐式生成默认的无参数构造函数?
一旦为类提供了任何构造函数,就不再生成隐式生成的无参数构造函数。 您为A
构造函数提供了重载,因此没有隐式生成无参数构造函数。
注1
使用Member Initializer List是告诉编译器使用构造函数的特定重载版本而不是默认的无参数构造函数的方法。
您必须使用初始化列表:
class B {
public:
B(int v) : a(v) { // here
}
private:
A a;
};
否则编译器将尝试使用默认构造函数构造A
由于您没有提供,因此会出现错误。
是的它可以,但是您没有为A
提供默认构造函数(没有参数或所有参数都有默认值),因此您只能在初始化列表中初始化它:
B(int v) : a(v)
{
}
这是因为构造体进入之前, a
将构造(或试图构建)用默认构造(这是不可用)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.