我有一个 A 类,它有两个静态变量。我想用另一个不相关的静态变量初始化一个,就像这样:
#include <iostream>
class A
{
public:
static int a;
static int b;
};
int A::a = 200;
int a = 100;
int A::b = a;
int main(int argc, char* argv[])
{
std::cout << A::b << std::endl;
return 0;
}
输出是 200。那么,谁能告诉我为什么?
最佳答案
根据查找规则,这是正确的。 [basic.lookup.unqual]/13说:
A name used in the definition of a static data member of class X (after the qualified-id of the static member) is looked up as if the name was used in a member function of X. [ Note: [class.static.data] further describes the restrictions on the use of names in the definition of a static data member. — end note ]
由于查找不合格的a
好像你在一个成员函数中,它必须首先找到成员A::a
. A::a
和 A::b
的初始化顺序不会影响查找,但会影响结果的定义程度。
关于c++ - 类静态变量初始化顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51279270/