我一直在阅读Herb Shutter的“Exceptional C ++”,“第1项:#define或const和inlining [...]”。
据说,类内初始化只允许用于整数类型(整数,字符,粗体),并且仅用于常量..
我只想知道为什么在类声明中无法初始化double / float。 有什么具体原因吗?
class EngineeringConstants { // this goes in the class
private: // header file
static const double FUDGE_FACTOR;
...
};
// this goes in the class implementation file
const double EngineeringConstants::FUDGE_FACTOR = 1.35;
我只是想知道不允许以下声明的原因:
class EngineeringConstants { // this goes in the class
private: // header file
static const double FUDGE_FACTOR = 1.35;
...
};
答案 0 :(得分:17)
此语句已过时:在C ++ 03中,不支持在类定义中使用double
进行初始化。在C ++中(从2011版开始),您可以在类定义中初始化任意成员。此外,初始化不仅限于static
成员,您还可以初始化非static
成员:
struct foo {
static constexpr double value = 1.23;
std::string str = "foo";
};
禁止在C ++ 03中使用浮点数初始化static
成员的历史原因是编译期间的数字可能与执行期间的数字不同。例如,当使用IEEE浮点在平台上进行交叉编译并使用IBM hex浮点定位平台时,即使对于两个数值系统中都可表示的常量,也会产生不同的结果。