首页 > 解决方案 > 在双重继承的情况下如何处理非标准构造函数

问题描述

我想C从两个类继承一个类AB其中一个 ( B) 具有非标准构造函数。look的构造函数应该如何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++inheritanceconstructorpolymorphismbase-class

解决方案


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

您可以通过适当的构造函数应用成员初始化器列表来初始化B基础子对象B。例如

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

推荐阅读