我在下面的代码中遇到了这个错误信息:
class Money {
public:
Money(float amount, int moneyType);
string asString(bool shortVersion=true);
private:
float amount;
int moneyType;
};
起初我以为在C++中不允许将默认参数作为第一个参数,但实际上是可以的。
我在下面的代码中遇到了这个错误信息:
class Money {
public:
Money(float amount, int moneyType);
string asString(bool shortVersion=true);
private:
float amount;
int moneyType;
};
起初我以为在C++中不允许将默认参数作为第一个参数,但实际上是可以的。
//bad (this won't compile)
string Money::asString(bool shortVersion=true){
}
//good (The default parameter is commented out, but you can remove it totally)
string Money::asString(bool shortVersion /*=true*/){
}
//also fine, but maybe less clear as the commented out default parameter is removed
string Money::asString(bool shortVersion){
}
bool shortVersion
参数,只需删除或注释掉= true
即可。 - Yacobystd::string Money::asString(bool)
。请注意,它甚至不包括参数的名称。事实上,在声明和定义中可以使用不同的名称。(在大型项目中,这很重要-出于任何原因-你想在定义中更改名称,但不希望重新编译依赖于声明的数百万行代码。) - sbi我最近犯了一个类似的错误,这是我解决它的方法。
当有一个函数原型和定义时,在定义中未指定默认参数。
例如:
int addto(int x, int y = 4);
int main(int argc, char** argv) {
int res = addto(5);
}
int addto(int x, int y) {
return x + y;
}