没有匹配函数来调用“X::X()”
no matching function for call to ‘X::X()’
我有一个包含基础和派生 class 的应用程序。我需要在派生的 class 中有一个基础文件,但在初始化它时遇到一些问题。这是代码:
#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;
}
错误:
/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)) ===|
您需要调用超类构造函数,因为默认构造函数不可用:
Y( int a ) : X(some_int_like_maybe_a), x( a ) { }
同时考虑将 X::X(int)
标记为 explicit
。
错误的原因是您没有构建 Y
的 X
部分。由于 Y
继承自 X
,因此您需要构造 Y
的 X
部分。因为你没有编译器为你做。当它这样做时,它使用了 X
没有的默认构造函数,因此你得到了错误。你需要有类似
的东西
Y( int a ) : X(some_value), x( a ) { }
构建Y
的X
部分和Y
的x
成员。或者您可以为 X 添加默认构造函数并让它默认构造。
我有一个包含基础和派生 class 的应用程序。我需要在派生的 class 中有一个基础文件,但在初始化它时遇到一些问题。这是代码:
#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;
}
错误:
/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)) ===|
您需要调用超类构造函数,因为默认构造函数不可用:
Y( int a ) : X(some_int_like_maybe_a), x( a ) { }
同时考虑将 X::X(int)
标记为 explicit
。
错误的原因是您没有构建 Y
的 X
部分。由于 Y
继承自 X
,因此您需要构造 Y
的 X
部分。因为你没有编译器为你做。当它这样做时,它使用了 X
没有的默认构造函数,因此你得到了错误。你需要有类似
Y( int a ) : X(some_value), x( a ) { }
构建Y
的X
部分和Y
的x
成员。或者您可以为 X 添加默认构造函数并让它默认构造。