当我在没有任何输入参数的情况下为 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 中调用。