为什么在类内初始化程序中不允许加倍

ATu*_*ngh 12 c++ oop

我一直在阅读Herb Shutter的"Exceptional C++","第1项:#define或const和inlining [...]".

据说,类内初始化仅允许用于整数类型(整数,字符,bool),并且仅用于常量.

我只想知道为什么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;
Run Code Online (Sandbox Code Playgroud)

我只是想知道不允许以下声明的原因:

class EngineeringConstants {      // this goes in the class
 private:                          // header file
  static const double FUDGE_FACTOR = 1.35;
  ...
 };
Run Code Online (Sandbox Code Playgroud)

Die*_*ühl 17

这个陈述已经过时了:在C++ 03 double中,不支持在类定义中使用s进行初始化.在C++中(从2011版开始),您可以在类定义中初始化任意成员.此外,初始化不仅限于static成员,您还可以初始化非static成员:

struct foo {
    static constexpr double value = 1.23;
    std::string   str = "foo";
};
Run Code Online (Sandbox Code Playgroud)

static在C++ 03中禁止使用浮点数初始化成员的历史原因是编译期间的数字可能与执行期间的数字不同.例如,当使用IEEE浮点在平台上进行交叉编译并使用IBM hex浮点定位平台时,即使对于两个数值系统中都可表示的常量,也会产生不同的结果.

  • @Nawaz:我确实认为它是_does_伤害因为它暗示C++ 11与C++不同,而不是.C++显然不是**C++ 03,我们将限定过时版本而不是当前版本!这就是"C++"而不是"C++ 11"的选择,你改变了答案,实际上是故意的. (3认同)
  • @computer:目前的官方C++标准是INCITS/ISO/IEC 14882-2011.早期版本可能仍在使用,但这并不意味着应该以有趣的方式引用标准的_current_版本. (2认同)