【问题标题】:C++ Inheritance: Error: candidate expects 1 argument, 0 provided [duplicate]C ++继承:错误:候选人需要1个参数,提供0 [重复]
【发布时间】:2018-04-20 13:49:53
【问题描述】:

在下面的程序中,我想从基类派生一个类。在我的代码中,一切似乎都很好。但是,我收到以下程序中显示的错误。请说明错误的原因,以及如何更正。

#include <iostream>
using namespace std;

struct Base
{
    int x;
    Base(int x_)
    {
        x=x_;
        cout<<"x="<<x<<endl;
    }
};

struct Derived: public Base
{
    int y;
    Derived(int y_)
    {
        y=y_;
        cout<<"y="<<y<<endl;
    }
};

int main() {
    Base B(1);
    Derived D(2);
}

这是错误:

Output:

 error: no matching function for call to 'Base::Base()
 Note: candidate expects 1 argument, 0 provided

【问题讨论】:

  • 你的基类的构造函数接受一个参数。因此,您的派生类必须适当地构造基类。有关详细信息,请参阅您的 C++ 书籍。

标签: c++ c++11 inheritance


【解决方案1】:

默认构造函数(即Base::Base())将用于初始化DerivedBase子对象,但Base没有。

您可以使用member initializer list 来指定应该使用Base 的哪个构造函数。例如

struct Derived: public Base
{
    int y;
    Derived(int y_) : Base(y_)
    //              ~~~~~~~~~~
    {
        y=y_;
        cout<<"y="<<y<<endl;
    }
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-22
    • 2012-02-11
    • 1970-01-01
    • 2019-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-28
    相关资源
    最近更新 更多