将其他参数作为默认值的函数参数

Function argument taking other argument as default value

我想要一个函数参数将另一个参数的值作为默认值。

我的问题是:为什么不允许我这样做?

void foo(int a, int b = a)
{

}

还有其他方法吗?

void foo(int a)
{
   foo(a,a);
}

void foo(int a, int b)
{

}

使用

void foo(int a, int b = a) { ... }

按照标准是一个错误。

来自 C++11 标准:

8.3.6 Default arguments

9 Default arguments are evaluated each time the function is called. The order of evaluation of function arguments is unspecified. Consequently, parameters of a function shall not be used in a default argument, even if they are not evaluated. Parameters of a function declared before a default argument are in scope and can hide namespace and class member names. [ Example:

int a;
int f(int a, int b = a); // error: parameter a
                         // used as default argument

...

— end example ]

  1. Why am i not allowed to do that ?

由于未指定函数参数的计算顺序,因此不能保证 b 将使用作为 a 的参数传入的值进行初始化。

来自 $8.3.6/9 默认参数 [dcl.fct.default]:

A default argument is evaluated each time the function is called with no argument for the corresponding parameter. A parameter shall not appear as a potentially-evaluated expression in a default argument.
[ Example:

int a;
int f(int a, int b = a);            // error: parameter a
                                    // used as default argument

  1. and is there an other way to do it than that ?

使用函数重载会简单而且很好。