在双重继承的情况下如何处理非标准构造函数

How to handle non-standard constructors in case of double inheritance

本文关键字:处理 构造函数 非标准 何处理 继承 情况下      更新时间:2023-10-16

我想从两个类AB继承一个类C,其中一个(B(有一个非标准的构造函数。C的构造函数应该如何看起来与两个基类中的任何一个兼容? 我有一个小例子来演示我的问题,它看起来像这样:

class A {
public:
A(){}
~A(){}
};
class B {
public:
B(int abc,
int def,
int ghj){}
~B(){}
};
class C:public B, public A {
public:
C(int test,
int test2,
int test3){}
~C(){}
};
int main(void) {
C* ptr = new C (123,456,789);
}

我在哪里得到以下编译器错误:

main.cpp: In constructor 'C::C(int, int, int)':
main.cpp:19:17: error: no matching function for call to 'B::B()'
int test3){}

给定C构造函数的当前实现,B(和A(的基本子对象将被默认初始化,但类B没有默认构造函数,这会导致错误。

您可以应用成员初始值设定项列表B通过适当的B构造函数初始化基子对象。

class C:public B, public A {
public:
C(int test,
int test2,
int test3) : B(test, test2, test3) {}
//               ^^^^^^^^^^^^^^^^^^^^^^^
~C(){}
};