[英]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;
}
compiler says: 编译说:
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&)
I've learned Java, and I don't know how to deal with this in C++. 我已经学习了Java,我不知道如何在C ++中处理这个问题。 Searching for a couple days, plz tell me can C++ do this?
搜索了几天,PLZ告诉我C ++可以这样做吗?
You need to use a Member Initialization List 您需要使用成员初始化列表
B(int v):a(v)
{
}
With: 附:
B(int v)
{
a = A(v); // i think this is the key point
}
a
is being assigned a value and not being initialized ( which is what you intend ), Once the body of an constructor begins {
, all its members are already constructed. a
被分配了一个值而没有被初始化 ( 这是你想要的 ),一旦构造函数的主体开始{
,它的所有成员都已经被构造。
Why do you get an error? 为什么会出错?
The compiler constructs a
before constructor body {
begins, the compiler uses the no argument constructor of A
because you didn't tell it otherwise Note 1 , Since the default no argument constructor is not available hence the error. 编译器构造
a
before构造函数体{
开始,编译器使用A
的无参数构造函数,因为你没有告诉它,否则注1 ,因为默认的无参数构造函数不可用因此错误。
Why is the default no argument constructor not generated implicitly? 为什么不隐式生成默认的无参数构造函数?
Once you provide any constructor for your class, the implicitly generated no argument constructor is not generated anymore. 一旦为类提供了任何构造函数,就不再生成隐式生成的无参数构造函数。 You provided overloads for constructor of
A
and hence there is no implicit generation of the no argument constructor. 您为
A
构造函数提供了重载,因此没有隐式生成无参数构造函数。
Note 1 注1
Using Member Initializer List is the way to tell the compiler to use particular overloaded version of the constructor and not the default no argument constructor. 使用Member Initializer List是告诉编译器使用构造函数的特定重载版本而不是默认的无参数构造函数的方法。
You have to use initialization lists: 您必须使用初始化列表:
class B {
public:
B(int v) : a(v) { // here
}
private:
A a;
};
Otherwise the compiler will try to construct an A
using the default constructor. 否则编译器将尝试使用默认构造函数构造
A
Since you don't provide one, you get an error. 由于您没有提供,因此会出现错误。
Yes it can, but you haven't provided a default constructor for A
(one that takes no parameters or all parameters have default values), so you can only initialize it in the initializer list : 是的它可以,但是您没有为
A
提供默认构造函数(没有参数或所有参数都有默认值),因此您只能在初始化列表中初始化它:
B(int v) : a(v)
{
}
This is because before the constructor body enters, a
will be constructed (or attempted to be constructed) with the default constructor (which isn't available). 这是因为构造体进入之前,
a
将构造(或试图构建)用默认构造(这是不可用)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.