【发布时间】:2012-02-04 06:44:48
【问题描述】:
我正在声明一个需要一些公共常量的类。我的想法是这样声明:
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
好吧,我确实了解此错误消息。它说我不能在类声明中声明浮点(非整数)常量。所以,问题是:为什么!?为什么可以是int 而不是float?
我知道如何解决这个问题。将 kFloatConst 声明为静态 const 成员,然后在 .cpp 中进行初始化可以解决问题,但这不是我想要的。我需要一个 compile time 常量(一个可以被编译器优化的),而不是一个需要 .obj 文件链接的常量类成员。
可以选择使用宏,但宏没有命名空间,我不喜欢全局定义的常量。
【问题讨论】:
-
见stackoverflow.com/questions/2454019/…>
-
查看这篇文章的第一个(已接受)答案:stackoverflow.com/questions/370283/…
-
你可以在类中初始化静态常量。
-
请参阅stackoverflow.com/questions/2454019/…,尤其是 Andreas Brinck 的回答。
-
@Pubby 我在问题中提到了这个解决方法。我不能接受这种方法。
标签: c++ visual-c++