gpt4 book ai didi

c++ - 为什么现有函数参数不能用于评估其他默认参数?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:05:06 25 4
gpt4 key购买 nike

我正在编写一个函数 foo(),它接受 2 个 const char* 作为参数,pBeginpEndfoo() 被传递了一个以 null 结尾的字符串。默认情况下,pEnd 指向字符串的 \0(最后一个字符)。

void foo (const char *pBegin,
const char *pEnd = strchr(pBegin, 0)) // <--- Error
{
...
}

但是,我在上面一行得到了一个错误:

error: local variable ‘pBegin’ may not appear in this context

为什么编译器不允许这样的操作?潜在的问题是什么?

最佳答案

该标准不仅明确禁止在默认参数表达式中使用其他参数,而且解释了原因并给出了示例:

ISO/IEC 14882:2003(E) - 8.3.6 Default arguments [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] ...

关于c++ - 为什么现有函数参数不能用于评估其他默认参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9146732/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com