我在声明一个需要一些公共常量的类。我的想法是,宣布的人就像这样:声明浮点常量的错误
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文件链接的常量类成员。
使用宏可能是一个选项,但宏没有命名空间,我不喜欢全局定义的常量。
请参阅 –
2012-02-04 06:49:41
看到这篇文章的第一个(接受)答案:http://stackoverflow.com/questions/370283/why-cant-i-have-a-non-integral-static-const-member-in-a-class – 2012-02-04 06:49:54
你可以在类中初始化静态常量。 – Pubby 2012-02-04 06:49:58