bpw*_*621 42 c++ arguments function
是否可以在函数参数列表中使用先前的参数作为参数列表中后续参数的默认值?例如,
void f( int a, int b = a, int c = b );
Run Code Online (Sandbox Code Playgroud)
如果可以,有任何使用规则吗?
Mik*_*our 63
答案是否定的,你不能.您可以使用重载获得所需的行为:
void f(int a, int b, int c);
inline void f(int a, int b) { f(a,b,b); }
inline void f(int a) { f(a,a,a); }
Run Code Online (Sandbox Code Playgroud)
至于最后一个问题,C根本不允许默认参数.
小智 30
不,这不是合法的C++.这在C++标准的8.3.6/9节中规定:
每次调用函数时都会计算默认参数.函数参数的评估顺序未指定.因此,函数的参数不应在默认参数表达式中使用,即使它们未被计算.
和:
int f(int a,int b = a); // error:参数a用作默认参数
而且C89至少不支持默认参数值.
作为潜在的解决方法,您可以:
const int defaultValue = -999; // or something similar
void f( int a, int b = defaultValue, int c = defaultValue )
{
if (b == defaultValue) { b = a; }
if (c == defaultValue) { c = b; }
//...
}
Run Code Online (Sandbox Code Playgroud)