【问题标题】:no matching function for call to ‘X::X()’没有调用“X::X()”的匹配函数
【发布时间】:2016-07-06 17:19:53
【问题描述】:

我有一个带有基类和派生类的应用程序。我需要在派生类中有一个基类文件,但是在初始化它时遇到了一些问题。代码如下:

#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)) ===|

【问题讨论】:

    标签: c++ inheritance initializer-list


    【解决方案1】:

    你需要调用超类的构造函数,因为默认构造函数不可用:

    Y( int a ) : X(some_int_like_maybe_a), x( a ) { }
    

    还可以考虑将X::X(int) 标记为explicit

    【讨论】:

      【解决方案2】:

      错误的原因是您没有构造YX 部分。由于Y 继承自X,您需要构造YX 部分。由于您没有编译器为您执行此操作。当它这样做时,它使用X 没有的默认构造函数,因此您会收到错误消息。你需要有类似的东西

      Y( int a ) : X(some_value), x( a ) { }
      

      构造YX 部分和Yx 成员。或者你可以为 X 添加一个默认构造函数,让它默认构造。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-10-16
        • 1970-01-01
        • 2021-09-21
        • 2016-11-23
        • 2016-08-08
        • 2014-03-12
        • 2015-03-17
        相关资源
        最近更新 更多