C++ 错误:为参数 1 提供的默认参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2545720/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 23:52:28  来源:igfitidea点击:

error: default argument given for parameter 1

c++functionmember-functionsdefault-arguments

提问by pocoa

I'm getting this error message with the code below:

我收到以下代码的错误消息:

class Money {
public:
    Money(float amount, int moneyType);
    string asString(bool shortVersion=true);
private:
    float amount;
    int moneyType;
};

First I thought that default parameters are not allowed as a first parameter in C++ but it is allowed.

首先我认为默认参数不允许作为 C++ 中的第一个参数,但它是允许的。

回答by Yacoby

You are probably redefining the default parameter in the implementation of the function. It should only be defined in the function declaration.

您可能正在重新定义函数实现中的默认参数。它应该只在函数声明中定义。

//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){
}