[英]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";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.