【问题标题】:Error declaring float constants声明浮点常量时出错
【发布时间】: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 文件链接的常量类成员。

可以选择使用宏,但宏没有命名空间,我不喜欢全局定义的常量。

【问题讨论】:

标签: c++ visual-c++


【解决方案1】:

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

然后有一个例外,即无论如何都允许使用整数常量。所以int 常量不是规则,而是例外。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-20
    • 2021-07-27
    • 1970-01-01
    • 1970-01-01
    • 2018-12-23
    相关资源
    最近更新 更多