C++ 继承 : Error: candidate expects 1 argument, 0 提供

标签 c++ c++11 inheritance

<分区>

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

#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 没有。

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

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

关于C++ 继承 : Error: candidate expects 1 argument, 0 提供,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47170154/

相关文章:

c++ - ElGamal 加密示例?

c++ - Rcpp 需要复制构造函数

c++ - 避免接受 lambda 的方法的 const/non-const 重复

c++ - c++中的细化和继承

c# - 如何设计一个特定的父类(super class)

language-agnostic - 我应该实例化一个集合还是从集合继承?

c++ - 为什么模板只能在头文件中实现?

c++ - 如何在 Vista 中使用 C++ 控制 PC 的风扇速度?

c++ - 如何从三个整数(或者可能是一个 git/SVN commit/rev.string)生成一个 constexpr 版本字符串?

c++ - 如何使用 make_pair 创建一对 id 和 struct(对象)?