静态const成员变量初始化 [英] static const member variable initialization
问题描述
好像我可以初始化POD静态const成员,但不能初始化其他类型:
Looks like I can init a POD static const member, but not other types:
struct C {
static const int a = 42; // OK
static const string b = "hi"; // compile error
};
为什么?
推荐答案
仅在整数和枚举类型中允许类定义中的语法 initializer
.对于 std :: string
,它必须在类定义之外定义并在那里初始化.
The syntax initializer in the class definition
is only allowed with integral and enum types. For std::string
, it must be defined outside the class definition and initialized there.
struct C {
static const int a = 42;
static const string b;
};
const string C::b = "hi"; // in one of the .cpp files
必须在一个翻译单元中定义
静态成员
才能满足一个定义规则.如果C ++允许以下定义;
static members
must be defined in one translation unit to fulfil the one definition rule. If C++ allows the definition below;
struct C {
static const string b = "hi";
};
b
将在包括头文件的每个翻译单元中定义.
b
would be defined in each translation unit that includes the header file.
C ++仅允许在类声明中将 integral
或 enumeration
类型的 const static
数据成员定义为快捷方式.无法定义其他类型的 const static
数据成员的原因是,需要进行非平凡的初始化(需要调用构造函数).
C++ only allows to define const static
data members of integral
or enumeration
type in the class declaration as a short-cut. The reason why const static
data members of other types cannot be defined is that non-trivial initialization would be required (constructor needs to be called).
这篇关于静态const成员变量初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!