我可以初始化 static const class 成员吗?

Can I initialize static const class member?

我要运行这个代码:

struct A {
    static const string d[] = {"1", "2"};    
};

并得到一个错误:

error: in-class initialization of static data member ‘const string A::d []’ of incomplete type
     static const string d[] = {"1", "2"};
                         ^
error: non-constant in-class initialization invalid for non-inline static member ‘A::d’
     static const string d[] = {"1", "2"};
                                        ^
note: (an out of class initialization is required)

Here 找资料说现在可以初始化我想要的东西了。那么问题是什么?

如果我添加 inline 那么它将起作用:

struct A {
    static const inline string d[] = {"1", "2"};    
};

UPD:我知道解决方法,但为什么 C++ 会那样工作?

如您所见,您可以使用 inline 或以下内容:

struct A {
    static const string d[];    
};

const string A::d[] = {"1", "2"};

在专用编译单元中(仅一次)。

Live Demo

标准明确指出 class 的 non-inline 静态数据成员只是声明,必须跟在命名空间范围的定义之后:class.static.data#3

3: The declaration of a non-inline static data member in its class definition is not a definition and may be of an incomplete type other than cv void. The definition for a static data member that is not defined inline in the class definition shall appear in a namespace scope enclosing the member's class definition. In the definition at namespace scope, the name of the static data member shall be qualified by its class name using the ​::​operator. The initializer expression in the definition of a static data member is in the scope of its class ([basic.scope.class]).

然后进一步细化这些规则,以便 non-volatile non-inline 整型或枚举类型的 const 静态数据成员可以用大括号初始化(实际上是在声明点定义变量):class.static.data#4

4: If a non-volatile non-inline const static data member is of integral or enumeration type, its declaration in the class definition can specify a brace-or-equal-initializer in which every initializer-clause that is an assignment-expression is a constant expression ([expr.const]). The member shall still be defined in a namespace scope if it is odr-used ([basic.def.odr]) in the program and the namespace scope definition shall not contain an initializer. An inline static data member may be defined in the class definition and may specify a brace-or-equal-initializer.

在 non-standardese 中,这表示除了整数或枚举的情况外,您必须与定义分开定义静态成员变量,这解释了您的示例失败的原因。