下面程序的输出应该是什么?
#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 classprocess
is defined in global scope; the notationprocess::run_chain
specifies that the memberrun_chain
is a member of classprocess
and in the scope of classprocess
. In the static data member definition, the initializer expression refers to the static data memberrunning
of classprocess
. —end example ]
关于c++ - 在静态成员变量初始值设定项中,为什么调用静态成员函数(不是全局函数)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36440927/