c++ - 类静态变量初始化顺序

标签 c++ scope language-lawyer

我有一个 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::aA::b 的初始化顺序不会影响查找,但会影响结果的定义程度。

关于c++ - 类静态变量初始化顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51279270/

相关文章:

c++ - 在 C++ 中提取 char 数组的 int

c++ - 使用boost的字节序转换

c++ - 运算符重载中没有运算符 '==' 匹配

c++ - 复制回调?

ruby - 如何将Regexp.last_match传递给Ruby中的 block

c++ - 阐明表达式的值类别

c++ - ISO C 中数组的左值到右值转换

c++ - math.h pow 与手动功率性能

ruby - 您可以在方法内部访问具有外部作用域的 Ruby 变量吗?

c++ - 可以将容器的复制构造函数定义为不可复制值类型的删除吗?