为什么允许这些默认参数? [英] Why are these default arguments allowed?

查看:242
本文介绍了为什么允许这些默认参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找到了这个问题,我完全感到不解。

I've found this question, and I'm completely baffled.

答案说: b 无效,非静态成员不能用作默认参数。这是完全有道理的。

The answer says b is invalid, "Non-static members can not be used as default arguments.". That makes perfect sense.

我不明白是为什么其他两个是好的。事实上,如果默认不是一个常量表达式,我很难理解语义是什么...

What I don't understand is why the other two are okay. In fact, I'm struggling to understand what the semantics are if the default is not a constant expression...

这里发生了什么?默认参数在编译时明确评估。编译器只是选择当前值?

What's going on here? Default parameters are clearly evaluated at compile time. Does the compiler simply pick the current value?

#include <iostream>

int g_x = 44; 

struct Foo 
{ 
  int m_x; 
  static int s_x; 

  Foo(int x) : m_x(x) {} 
  int a(int x = g_x) { return x + 1; } 
  int b(int x = m_x) { return x + 1; }
  int c(int x = s_x) { return x + 1; }
}; 

int Foo::s_x = 22; 

int main(int argc, char** argv) 
{ 
  Foo f(6); 

  std::cout << f.a() << std::endl; 
  std::cout << f.b() << std::endl; 
  std::cout << f.c() << std::endl; 

  return 0; 
}


推荐答案

实际上,当函数被调用时,这就是为什么这是好的。从 C ++标准草稿部分 8.3 .6 的默认参数(强调我的进展):

Actually, default arguments are evaluated when the function is called, which is why this is okay. From the draft C++ standard section 8.3.6 Default arguments which says (emphasis mine going forward):


每次调用函数时都会计算默认参数。函数参数的求值顺序未指定。
因此,一个函数的参数不能在默认的
参数中使用,即使它们没有被求值。在默认参数之前声明的函数
的参数在范围内,并且可以隐藏命名空间
和类成员名。

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.

下面的例子从同一节给我们为什么我们可以使用静态成员但不是非静态成员的理由:

The following example from the same section gives us a rationale for why we can use static members but not non-static ones:


示例:以下示例中的X :: mem1()的声明为
,因为没有为非静态成员提供对象
X :: a用作初始化程序。

[ Example: the declaration of X::mem1() in the following example is ill-formed because no object is supplied for the non-static member X::a used as an initializer.

int b;
class X {
    int a;
    int mem1(int i = a); // error: non-static member a
                         // used as default argument
    int mem2(int i = b); // OK; use X::b
    static int b;
};

X :: mem2()的声明是有意义的,需要b $ b才能访问静态成员X :: b。类,对象和
成员在第9节中描述。​​-end example]

The declaration of X::mem2() is meaningful, however, since no object is needed to access the static member X::b. Classes, objects, and members are described in Clause 9. —end example ]

这篇关于为什么允许这些默认参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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