为什么不允许静态常量浮点数?
我有一个类,它本质上只是包含一堆在我的应用程序中使用的常量定义.但出于某种原因,long
可以编译但 float
不能:
I have a class which is essentially just holds a bunch of constant definitions used through my application. For some reason though, long
s compile but float
s do not:
class MY_CONSTS
{
public :
static const long LONG_CONST = 1; // Compiles
static const float FLOAT_CONST = 0.001f; // C2864
};
出现以下错误:
1>c:projectsmyprojectConstant_definitions.h(71) : error C2864: 'MY_CONSTS::FLOAT_CONST' : only static const integral data members can be initialized within a class
我错过了什么吗?
推荐答案
回答你提出的实际问题:因为标准是这么说的".
To answer the actual question you asked: "because the standard says so".
只有静态、常量、整型 类型(包括枚举)的变量可以在类声明中初始化.如果编译器支持浮点数的内联初始化,则它是一个扩展.正如其他人指出的那样,处理静态、常量、非整型变量的方法是在类的相应源文件(而不是头文件)中定义和初始化它们.
Only variables of static, constant, integral types (including enumerations) may be initialized inside of a class declaration. If a compiler supports in-line initialization of floats, it is an extension. As others pointed out, the way to deal with static, constant, non-integral variables is to define and initialize them in the class's corresponding source file (not the header).
C++ 标准第 9.2 节类成员"第 4 项:
C++ Standard Section 9.2 "Class Members" item 4:
member-declarator 可以包含一个constant-initializer 仅当它声明了一个静态成员(9.4)const 积分或 const 枚举类型,见 9.4.2.
A member-declarator can contain a constant-initializer only if it declares a static member (9.4) of const integral or const enumeration type, see 9.4.2.
第 9.4.2 节静态数据成员"第 2 项:
Section 9.4.2 "Static Data Members" item 2:
如果静态数据成员是 const整数或常量枚举类型,它在类定义中的声明可以指定一个常量初始化器这应该是一个积分常数表达式 (5.19).在这种情况下,成员可以出现在积分常数中表达式.该成员仍将是如果它是在命名空间范围中定义的在程序和命名空间中使用范围定义不应包含初始化器.
If a static data member is of const integral or const enumeration type, its declaration in the class de?nition can specify a constant-initializer which shall be an integral constant expression (5.19). In that case, the member can appear in integral constant expressions. The member shall still be de?ned in a namespace scope if it is used in the program and the namespace scope de?nition shall not contain an initializer.
相关文章