error:为参数1指定的默认参数

poc*_*coa 83 c++ function member-functions default-arguments

我收到此错误消息,代码如下:

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

首先,我认为默认参数不允许作为C++中的第一个参数,但允许使用.

Yac*_*oby 183

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

//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){
}
Run Code Online (Sandbox Code Playgroud)

  • @pocoa:实际上,它确实有意义.如果为参数提供默认值,则会在_caller_中填入这些值.所以他们_have_在函数的声明中,因为这是调用者需要看到的.如果你必须在_definition_重复它们,那将是多余的,更难以维护.(这也是我不同意Yacoby关于在实现中评论默认参数的原因.IME,在实际项目中这样的评论迟早会与声明不同步. (4认同)
  • 实际定义是`std::string Money::asString(bool)`。请注意,它甚至不包括参数的名称。而且,实际上,您可以在声明中使用与定义中不同的名称。(这在大型项目中很重要,无论出于何种原因,您想更改定义中的名称,但又不想重新编译数百万行依赖于声明的代码。) (2认同)

小智 16

我最近犯了类似的错误。这就是我解决它的方法。

当有函数原型和定义时。定义中未指定默认参数。

例如:

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;
}
Run Code Online (Sandbox Code Playgroud)