C++ 默认函数参数

标签 c++

我想实现这个:

- second parameter by default set to first argument

类似于:

int foo (int a, int b = a);

但是怎么做呢?

非常感谢!

最佳答案

这是被禁止的:

8.3.6 默认参数 [dcl.fct.default]

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 default argument expressions, even if they are not evaluated. Parameters of a function declared before a default argument expression 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

typedef int I;

int g( float I , int b = I (2)); / / error: parameter I found

int h(int a , int b = sizeof (a )); / / error, parameter a used

/ / in default argument

—end example ]

另一种是重载:

int foo(int a, int b);

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

关于C++ 默认函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12847456/

相关文章:

c++ - 错误 C1083 : Cannot open include file: 'FL/Fl.h' : No such file or directory

c++ - 如何从 rapidjson::Document 获取中文 wstring?

c++ - OpenGL 透明效果在 Meego 上显示的很糟糕

c++ - 如何通过读取文件来填充 vector ?

c++:没有重载函数的实例?

C++ 类方法继承

c++ - Rcpp:安装带有静态库的包,以便独立于平台使用

c++ - 按键多次扫描

c++ - 对象/指针 vector 的问题(实现复合设计模式)

c++ - 如何使用 Boost::Asio 访问 Web 服务?