为什么不允许使用静态const浮点数? [英] Why aren't static const floats allowed?

查看:136
本文介绍了为什么不允许使用静态const浮点数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类,该类实际上只包含一堆通过我的应用程序使用的常量定义。但是由于某些原因, long s会编译,但 float s不会编译:

I have a class which is essentially just holds a bunch of constant definitions used through my application. For some reason though, longs compile but floats do not:

class MY_CONSTS
{
public :
    static const long   LONG_CONST = 1;      // Compiles 
    static const float FLOAT_CONST = 0.001f; // C2864
};

给出以下错误:

1>c:\projects\myproject\Constant_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:


成员声明符可以包含
constant-initializer 仅当声明
const整数或const枚举
类型的静态成员(9.4)时,请参见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
整数或const枚举类型,则
在类定义
中的声明可以指定 constant-initializer
应为整数常量
表达式(5.19)。在这种情况下,
成员可以出现在整数常量
表达式中。如果程序中使用了
,则该成员仍应在
中定义,并且该命名空间
范围定义中不应包含
initializer

这篇关于为什么不允许使用静态const浮点数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆