2012-02-04 90 views
0

我在声明一个需要一些公共常量的类。我的想法是,宣布的人就像这样:声明浮点常量的错误

class MyClass { 
public: 
    const int kIntConst = 1234; 
    const float kFloatConst = 1234.567f; 
    // ...methods... 
}; 

这种方法工作正常int不变,但失败了float一个具有以下错误:

error C2864: 'MyClass::kFloatConst' : only static const integral data members can be initialized within a class 

嗯,我了解此错误信息。它说我不能在类声明中声明一个float(非整数)常量。所以,问题是:为什么!?为什么它可以是int但不是float

我知道如何解决这个问题。声明kFloatConst为静态const成员,后来在.cpp中初始化解决了这个问题,但这不是我想要的。我需要一个编译时间常量(可以通过编译器优化的一个),而不是需要.obj文件链接的常量类成员。

使用宏可能是一个选项,但宏没有命名空间,我不喜欢全局定义的常量。

+1

请参阅 2012-02-04 06:49:41

+1

看到这篇文章的第一个(接受)答案:http://stackoverflow.com/questions/370283/why-cant-i-have-a-non-integral-static-const-member-in-a-class – 2012-02-04 06:49:54

+0

你可以在类中初始化静态常量。 – Pubby 2012-02-04 06:49:58

回答

2

一般规则是你不能在类声明中定义常量。

然后,有一个例外,积分常数无论如何。所以int常数不是规则,而是例外。

+0

谢谢。评论中提供的链接给了我明确的答案。 – real4x 2012-02-04 21:53:57