我想从两个类A
和B
继承一个类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(){}
};