c++ - 在静态成员变量初始值设定项中,为什么调用静态成员函数(不是全局函数)?

标签 c++ static language-lawyer static-methods

下面程序的输出应该是什么?

#include<iostream>

int foo()
{
  return 10;
}

struct foobar
{
  static int x;
  static int foo()
  {
    return 11;
  }
};

int foobar::x = foo();

int main()
{
  std::cout<<foobar::x<<endl;
}

我已经运行程序但得到答案11,但我认为正确答案应该是10。我不知道为什么 int foobar::x = foo(); 中的 foo() 应该是静态函数,请帮助我理解这一点。更多关于使用静态函数的示例将是首选!

最佳答案

因为初始化表达式在struct foobar的范围内,所以foobar::foo()会在这里被调用。

根据标准,$9.4.2/2 静态数据成员 [class.static.data]:

The initializer expression in the definition of a static data member is in the scope of its class (3.3.7). Example:

class process {
static process* run_chain;
static process* running;
};
process* process::running = get_main();
process* process::run_chain = running;

The static data member run_chain of class process is defined in global scope; the notation process::run_chain specifies that the member run_chain is a member of class process and in the scope of class process. In the static data member definition, the initializer expression refers to the static data member running of class process. —end example ]

关于c++ - 在静态成员变量初始值设定项中,为什么调用静态成员函数(不是全局函数)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36440927/

相关文章:

c++ - do-while-false 循环是否常见?

C++11 "auto"语义

c++ - std(boost)::filesystem::path 组件数

我们可以在 C 的不同函数中声明相同的局部静态变量吗?

c++ - 当显式模板实例化定义先于显式声明时,GCC 和 clang 不同意

C++应用程序仅在关闭时才在串行上发送数据

c++ - 内联函数返回静态创建的对象

.net - 是否可以在 C++/CLI 环境中创建静态字典?

c++ - 类型名、类型成员和非类型成员 : is it valid code?

c++ - const 是否允许在此处进行(理论上的)优化?