我收到以下代码的错误消息:
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){
}
I made a similar error recently. this is how I resolved it.
when having a function prototype and definition. the default parameter is not specified in the definition.
eg:
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;
}