c++ - 在双重继承的情况下如何处理非标准构造函数
问题描述
我想C
从两个类继承一个类A
,B
其中一个 ( 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){}
解决方案
给定 的构造函数的当前实现,(and )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(){}
};
推荐阅读
- r - 添加示例时,pkgdown 无法解析 Rd 文件
- python - 具有递归函数的 P(n) 之和
- powershell - powershell sendkeys 不能与阿拉伯字符一起正常工作
- sql-server - SQL Server 表中列的整理设置不起作用
- php - PHP-SPX - 在 Web GUI 上查看 CLI 命令生成的分析结果
- django - 如何根据用户状态呈现不同的模板
- javascript - Karma - 调度点击事件时没有调用 Jasmine 间谍
- linux - 从 cron 执行时脚本无法正确运行
- javascript - 如何在瞬间自定义“无效日期”
- azure-devops - 有没有办法在 Azure DevOps 中将 PR 从特定分支限制到另一个分支