看起来我可以初始化一个 POD 静态常量成员,但不能初始化其他类型:
struct C {
static const int a = 42; // OK
static const string b = "hi"; // compile error
};
为什么?
最佳答案
类定义中的语法 initializer
只允许用于整型和枚举类型。对于 std::string
,它必须在类定义之外定义并在那里初始化。
struct C {
static const int a = 42;
static const string b;
};
const string C::b = "hi"; // in one of the .cpp files
static members
必须在一个翻译单元中定义才能满足一个定义规则。如果 C++ 允许下面的定义;
struct C {
static const string b = "hi";
};
b
将在包含头文件的每个翻译单元中定义。
C++ 仅允许在类声明中定义integral
或enumeration
类型的const static
数据成员作为快捷方式。之所以不能定义其他类型的const static
数据成员,是因为需要进行非平凡的初始化(需要调用构造函数)。
关于c++ - static const 成员变量初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24798761/