Class inherited from class without default constructor(从没有默认构造函数的类继承的类)
问题描述
现在我有一个从 B
类继承的 A
类,并且 B
没有默认构造函数.我正在尝试为 A
创建一个构造函数,它与 B
的构造函数
Right now I have a class A
that inherits from class B
, and B
does not have a default constructor. I am trying the create a constructor for A
that has the exact same parameters for B
's constructor
struct B {
int n;
B(int i) : n(i) {}
};
struct A : B {
A(int i) {
// ...
}
};
但我明白了:
error: no matching function for call to ‘B::B()’
note: candidates are: B::B(int)
我该如何解决这个错误?
How would I fix this error?
推荐答案
构造函数应该是这样的:
The constructor should look like this:
A(int i) : B(i) {}
冒号后面的位表示使用其int
构造函数初始化该对象的B基类子对象,值为i".
The bit after the colon means, "initialize the B base class sub object of this object using its int
constructor, with the value i".
我猜您没有为 B 提供初始化程序,因此默认情况下编译器会尝试使用不存在的无参数构造函数对其进行初始化.
I guess that you didn't provide an initializer for B, and hence by default the compiler attempts to initialize it with the non-existent no-args constructor.
这篇关于从没有默认构造函数的类继承的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从没有默认构造函数的类继承的类


基础教程推荐
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- CString 到 char* 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01