C++ 实例化新对象时不接受继承方法默认参数值

C++ Inheritance methods default argument value not accepted when instantiating a new object

本文关键字:继承 不接受 方法 默认 参数 新对象 实例化 对象 C++      更新时间:2023-10-16

我有一个Regular类。它有一个setValue方法:

void Regular::setValue(string id, string name, double s, int n = 0)
{
uid = id;
uname = name;
sid = s;
netcount = n;
}

当我运行以下代码时

Regular x;
x.setValue("X01", "John Doe", 1.1);

它给了我一个错误

'Regular::setValue': function does not take 3 arguments 

它不应该默认设置netcount = 0的值,因为我没有传入第四个参数吗?

此代码段应该可以解决您的问题。仅在声明中,您需要指定为默认参数。

#include <iostream>
#include <string>
using namespace std;
class Regular {
string uid;
string uname;
double sid;
int netcount;
public:
void setValue(string id, string name, double s, int n = 0);
};

void Regular::setValue(string id, string name, double s, int n)
{
uid = id;
uname = name;
sid = s;
netcount = n;
}
int main()
{
Regular x;
x.setValue("X01", "John Doe", 1.1);
return 0;
}