类继承自没有默认构造函数的类

类继承自没有默认构造函数的类

问题描述:

现在我有一个类 A 继承自 B B 没有默认构造函数。我试着创建一个 A 的构造函数,它具有与 B 的构造函数完全相同的参数,但我得到:

Right now I have a class A that inherits from class B, and B does not have a default constructor. I am trying the create a constructor for A that has the exact same parameters for B's constructor, but I get:

error: no matching function for call to ‘B::B()’
note: candidates are: B::B(int)

如何修复此错误?

构造函数应如下所示:

A(int i) : B(i) {}

冒号后的位表示这个对象的B基类子对象使用它的 int 构造函数,值为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".

您没有为B提供初始化程序,因此默认情况下,编译器尝试使用不存在的无参数构造函数初始化它。

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.