class Money {
public:
Money(float amount, int moneyType);
string asString(bool shortVersion=true);
private:
float amount;
int moneyType;};
如上图的红色代码。会出现 error: default argument given for parameter 1 错误,这是因为有默认参数的函数在声明和定义的时候有点小坑。
正确的做法是:1.在声明的同时就定义。
2.先声明再定义的情况下,定义的时候需要:
//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){}
本文探讨了C++中带有默认参数的成员函数在声明与定义时可能出现的问题,并提供了几种有效的解决方案。
1226

被折叠的 条评论
为什么被折叠?



