在基类构造函数中使用参数时C++继承编译器错误
C++ inheritance compiler error when using parameter in base class constructor
当我定义没有任何输入参数的 c1 构造函数时,此代码将编译。当我定义构造函数以接受输入参数时,它不会编译。
# include "c1.hh"
int main() {
int b = 1;
c1 a(b);
}
# ifndef c1_hh
# define c1_hh
c1.hh:
# include <iostream>
class c1 {
public:
c1(int a);
~c1();
};
# endif
c1.cc:
# include "c1.hh"
c1::c1(int a) {
std::cout << "c1 init n";
std::cout << a;
}
c1::~c1()
{}
c2.hh:
# ifndef c2_hh
# define c2_hh
# include "c1.hh"
class c2 : public c1 {
c2();
~c2();
};
# endif
c2.cc:
# include "c2.hh"
c2::c2 () {
std::cout << "c2 init n";
}
c2::~c2() {}
编译器错误:
c2.cc: In constructor ‘c2::c2()’:
c2.cc:3:9: error: no matching function for call to ‘c1::c1()’
c2.cc:3:9: note: candidates are:
c1.hh:9:3: note: c1::c1(int)
c1.hh:9:3: note: candidate expects 1 argument, 0 provided
c1.hh:7:7: note: c1::c1(const c1&)
c1.hh:7:7: note: candidate expects 1 argument, 0 provided
为什么它试图调用 c1::c1()?它永远不会从 c2.cc 调用。
问题是
当您自己定义C1::C1(int)
时,编译器不会再为您生成C1::C1()
。
定义 C2::C2()
时,默认情况下需要C1::C1()
,因为如果您没有在 C2::C2()
中指定 C1
的特定构造函数,它是 C2
的父级。
子类的所有构造函数都将调用父类的构造函数之一。如果未显式指定要使用的超类构造函数,则默认为不带参数的构造函数。
下面是使代码有效的两个示例:
c2::c2 () : c1(5) {
std::cout << "c2 init n";
}
或
c2::c2 (int a) : c1(a) {
std::cout << "c2 init n";
}
相关文章:
- 继承函数的重载解析
- 继承期间显示未知行为的子类
- 头文件-继承c++
- 为什么在保护模式下继承升级不起作用
- 通过继承类使用来自不同命名空间的运算符
- 子目录是否继承属性,例如add_definitions,include_directories和父Cmakelist.t
- 混合组合和继承的C++问题
- 继承:构造函数,初始化C++11中基类的类C数组成员
- 从类继承时,继承的类是否会通过父类重新定义继承的变量
- 公共与私人继承
- 如何创建从同一类继承的不同对象的向量
- 如何从另一个文件继承私有成员变量和公共函数
- 在模板基类中为继承类中的可选重写生成虚拟方法
- 带有继承的C++工厂
- 我应该避免多重实现继承吗
- C++继承更改成员
- 从具有默认值的部分指定模板类继承时发生SWIG错误,具有不带默认值的正向声明
- 关于C++中具有多重继承"this"指针的说明
- 尝试使用继承和模板实现CRTP.Visual Studio正在生成编译器错误
- 如何在QT Creator上将QWidget声明为继承类的对象