C++ 继承:错误:候选人需要 1 个参数,提供 0
C++ Inheritance: Error: candidate expects 1 argument, 0 provided
在下面的程序中,我想从基类派生一个类。在我的代码中,一切似乎都很好。但是,我在以下程序中显示错误。请解释错误的原因以及如何更正。
#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()
) 将用于初始化 Derived
的 Base
子对象,但Base
没有子对象。
可以使用成员初始值设定项列表来指定应使用Base
的哪个构造函数。
struct Derived: public Base
{
int y;
Derived(int y_) : Base(y_)
// ~~~~~~~~~~
{
y=y_;
cout<<"y="<<y<<endl;
}
};
相关文章:
- 何时提供默认参数作为模板参数
- C++有什么方法可以在既不调用函数模板也不提供其模板参数的情况下引用函数模板?
- 如何在C++中提供模板化函数作为另一个函数的参数,默认值?
- 执行参数未提供预期结果
- 提供变量作为 MATLAB 系统命令的输入参数,以便C++可执行文件
- 当为模板参数提供默认参数时,VS 2017无法正确找到以前定义的类型
- 确保std::bind提供正确数量的参数
- 是否可以在不扩展初始宏的情况下将一个宏作为参数提供给另一个宏?
- const 数组,用于在数组长度定义中使用其元素或为模板参数提供值
- 将 std::function 的参数作为参数提供给新对象的前向参数
- 在C++容器中,作为模板参数提供的分配器和作为构造函数参数提供的分配程序之间的区别
- 如何为函数中的矢量参数提供默认值
- 如何将参数提供给期望所有常量值的方法
- V8如何获取作为参数提供的对象键值
- 如何给一个变量的默认值,如果没有参数提供给构造函数?c++
- 如何从函数中获取替代值,该函数通过非常量输出参数提供所需数据,以便为其分配对常量变量的引用
- 如果URL作为参数提供,c++ curl无法解析host
- 在编译时产生相同类型的std::元组,给定其长度,由模板参数提供
- MPI 发送消息或将其作为参数提供
- G++ 使用模板参数提供"unresolved overloaded function type"