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

在基类构造函数中使用参数时C++继承编译器错误,c++,C++,当我在没有任何输入参数的情况下为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 c2.cc: #

当我在没有任何输入参数的情况下为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
c2.cc:

# include "c2.hh"    

c2::c2 () {

  std::cout << "c2 init \n";    
}

c2::~c2()  {}
为什么它试图调用c1::c1?它从不从c2.cc调用

问题是

当您自己定义C1::C1int时,编译器将不再为您生成C1::C1


定义C2::C2时,默认情况下需要C1::C1,因为如果未在C2::C2中指定C1的特定构造函数,则它是C2的父类。

子类的所有构造函数都将调用父类的一个构造函数。如果没有显式指定要使用哪个超类的构造函数,则默认为不带参数的构造函数

下面是两个使您的代码有效的示例:

c2::c2 () : c1(5) {
  std::cout << "c2 init \n";    
}

# 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
c2::c2 () : c1(5) {
  std::cout << "c2 init \n";    
}
c2::c2 (int a) : c1(a) {
  std::cout << "c2 init \n";    
}