我一直在读Herb Shutter的"Exceptional C++“,"Item 1:#define or const and 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;
...
};发布于 2013-09-29 00:14:25
此语句已过时:在C++03中,不支持在类定义中使用double%s进行初始化。在C++ (从2011版本开始)中,您可以在类定义中初始化任意成员。此外,初始化不限于static成员,但您也可以初始化非static成员:
struct foo {
static constexpr double value = 1.23;
std::string str = "foo";
};禁止在C++03中使用浮点数初始化static成员的历史原因是,编译期间的数值可能与执行期间的数值不同。例如,当在使用IEEE浮点的平台和使用IBM十六进制浮点的平台上进行交叉编译时,即使对于可以在两个数字系统中表示的常量,也会产生不同的结果。
https://stackoverflow.com/questions/19068905
复制相似问题