Bri*_*own 0 c++ inheritance initializer-list
我有一个基础和派生类的应用程序.我需要在派生类中有一个基类的字段,但是在初始化它时会遇到一些问题.这是代码:
#include <iostream>
using namespace std;
class X
{
public :
X( int x ) { }
} ;
class Y : public X
{
X x ;
Y* y ;
Y( int a ) : x( a ) { }
} ;
int main()
{
return 0;
}
Run Code Online (Sandbox Code Playgroud)
而错误:
/tmp/test.cpp||In constructor ‘Y::Y(int)’:|
/tmp/test.cpp|14|error: no matching function for call to ‘X::X()’|
/tmp/test.cpp|14|note: candidates are:|
/tmp/test.cpp|7|note: X::X(int)|
/tmp/test.cpp|7|note: candidate expects 1 argument, 0 provided|
/tmp/test.cpp|4|note: X::X(const X&)|
/tmp/test.cpp|4|note: candidate expects 1 argument, 0 provided|
||=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|
Run Code Online (Sandbox Code Playgroud)
您需要调用超类构造函数,因为默认构造函数不可用:
Y( int a ) : X(some_int_like_maybe_a), x( a ) { }
Run Code Online (Sandbox Code Playgroud)
还要考虑标记X::X(int)为explicit.
错误的原因是你没有构建X部分Y.由于你的Y继承X需要构建X部分Y.既然你没有,编译器会为你做.当它这样做时,它使用默认构造函数,它X没有,因此你得到错误.你需要有类似的东西
Y( int a ) : X(some_value), x( a ) { }
Run Code Online (Sandbox Code Playgroud)
构建X部分Y和x成员Y.或者您可以为X添加默认构造函数,并让它默认构造.