是否可以使用另一个参数初始化C ++默认参数? [英] Can a C++ default argument be initialized with another argument?

查看:100
本文介绍了是否可以使用另一个参数初始化C ++默认参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于C ++中的默认参数,该值是否需要是一个常量,或者是另一个参数吗?



也就是说, >

  RateLimiter(unsigned double rateInPermitsPerSecond,
unsigned int maxAccumulatedPermits = rateInPermitsPerSecond);

目前我收到一个错误:



< >

RateLimiter.h:13:错误:'rateInPermitsPerSecond'未在此范围内声明



解决方案

另一个参数不能用作默认值。标准状态:



b 9 每次当相应的
参数没有参数时调用一个默认参数。函数参数的求值顺序未指定。因此,
函数的参数不应在默认参数中使用,即使它们未被求值。


使用以下示例说明它:

  int f(int a,int b = a); //错误:参数a 
//用作默认参数


For a default argument in C++, does the value need to be a constant or will another argument do?

That is, can the following work?

RateLimiter(unsigned double rateInPermitsPerSecond, 
            unsigned int maxAccumulatedPermits = rateInPermitsPerSecond);

Currently I am getting an error:

RateLimiter.h:13: error: ‘rateInPermitsPerSecond’ was not declared in this scope

解决方案

Another argument cannot be used as the default value. The standard states:

8.3.6 Default arguments
...
9 A default argument is evaluated each time the function is called with no argument for the corresponding parameter. 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.

and illustrates it with the following sample:

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

这篇关于是否可以使用另一个参数初始化C ++默认参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆