简体   繁体   English

声明浮点常量时出错

[英]Error declaring float constants

I'm declaring a class which needs some public constants. 我正在声明一个需要一些公共常量的类。 My idea was declaring ones just like this: 我的想法是宣布这样的:

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

This approach works fine for int constant but fails for the float one with the following error: 这种方法适用于int常量,但对于float失败,出现以下错误:

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

Well, I do understand this error message. 好吧,我确实理解这个错误信息。 It says I cannot have a float (non-integral) constant declared in the class declaration. 它说我不能在类声明中声明一个float(非整数)常量。 So, the question is: WHY!? 所以,问题是:为什么!? Why it can be int but not float ? 为什么它可以是int而不是float

I know how to workaround this. 我知道如何解决这个问题。 Declaring kFloatConst as a static const member and later initialization in .cpp solves the problem but this is not what I'd like to have. kFloatConst声明为静态const成员并稍后在.cpp中初始化可以解决问题,但这不是我想要的。 I need a compile time constant (a one which can be optimized by compiler), not a constant class member which needs .obj file linking. 我需要一个编译时常量(一个可以通过编译器优化的常量),而不是需要.obj文件链接的常量类成员。

Using macro could be an option but macro doesn't have namespace and I don't like globally defined constants. 使用宏可能是一个选项,但宏没有命名空间,我不喜欢全局定义的常量。

The general rule is that you cannot have constants defined inside the class declaration. 一般规则是您不能在类声明中定义常量。

Then there is an exception that integral constants are allowed anyway. 然后有一个例外,即无论如何允许积分常数。 So the int constant isn't the rule, but the exception. 所以int常量不是规则,而是异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM