[英]Class inherited from class without default constructor
Right now I have a class A
that inherits from class B
, and B
does not have a default constructor.现在我有一个继承自B
类的A
类,而B
没有默认构造函数。 I am trying the create a constructor for A
that has the exact same parameters for B
's constructor我正在尝试为A
创建一个构造函数,该构造函数与B
的构造函数具有完全相同的参数
struct B {
int n;
B(int i) : n(i) {}
};
struct A : B {
A(int i) {
// ...
}
};
but I get:但我得到:
error: no matching function for call to ‘B::B()’
note: candidates are: B::B(int)
How would I fix this error?我将如何修复此错误?
The constructor should look like this:构造函数应如下所示:
A(int i) : B(i) {}
The bit after the colon means, "initialize the B base class sub object of this object using its int
constructor, with the value i".冒号后面的位表示“使用其int
构造函数初始化此对象的 B 基类子对象,值为 i”。
I guess that you didn't provide an initializer for B, and hence by default the compiler attempts to initialize it with the non-existent no-args constructor.我猜您没有为 B 提供初始化程序,因此默认情况下编译器会尝试使用不存在的 no-args 构造函数初始化它。
You need to invoke the base constructor via your class' initializer list.您需要通过类的初始值设定项列表调用基本构造函数。
Example:例子:
class C : public B
{
public:
C(int x) : B(x)
{
}
};
When you don't initialize B explicitly it will try to use the default constructor which has no parameters.当您不显式初始化 B 时,它将尝试使用没有参数的默认构造函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.