简体   繁体   中英

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:

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. So, the question is: WHY!? Why it can be int but not 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. I need a compile time constant (a one which can be optimized by compiler), not a constant class member which needs .obj file linking.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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