C++ 继承:错误:候选人需要 1 个参数,提供 0

C++ Inheritance: Error: candidate expects 1 argument, 0 provided

本文关键字:参数 提供 继承 错误 候选人 C++      更新时间:2023-10-16

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

#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

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

可以使用成员初始值设定项列表来指定应使用Base的哪个构造函数。

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