在基类构造函数中使用参数时C++继承编译器错误

C++ inheritance compiler error when using parameter in base class constructor

本文关键字:C++ 继承 编译器 错误 参数 基类 构造函数      更新时间:2023-10-16

当我定义没有任何输入参数的 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";    
}