gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 02:05:02 26 4
gpt4 key购买 nike

我想从两个类 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 没有默认构造函数,这会导致错误。

您可以申请 member initializer list通过 B 的适当构造函数初始化 B 基础子对象。例如

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

关于c++ - 在双重继承的情况下如何处理非标准构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52564242/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com