我一直在阅读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浮点定位平台时,即使对于两个数值系统中都可表示的常量,也会产生不同的结果.