是否需要单独定义C++中的类或结构的常量静态成员变量?

Kri*_*nan 0 c++ static const

是否需要单独定义C++中的类或结构的常量静态成员变量?

它是否正确?

struct test
{
    const static int x;
};

int test::x;
Run Code Online (Sandbox Code Playgroud)

CB *_*ley 5

不,这不正确.定义必须声明匹配,并且xconst int不是int.作为constPOD类型的变量,它还需要初始化.例如

const int test::x = 0;
Run Code Online (Sandbox Code Playgroud)

作为const static整数类型的成员,也允许在类的定义中提供初始化器.

  • @Krishnan:如果它们是`const` integral或`const`枚举类型的`static`成员,则只允许初始化类主体中的数据成员.`std :: string`不符合这些要求.您链接到的问题的接受答案正好说明了这一点. (2认同)