class MyClass { private: static const int intvalue= 50; static const float floatvalue = 0.07f; };
如上申请方式导致错误
error C2864: 'MyClass::floatvalue : only static const integral data members can be initialized within a class
1. 尝试使用 static constexpr float floatvalue = 0.5f;
error C4430: 缺少类型说明符 - 假定为 int。注意: C++ 不支持默认 int error C2144: 语法错误:“float”的前面应有“;”
2. MyClass.h
class MyClass { private: static const int intvalue = 50; // can provide a value here (integral constant) static const float floatvalue; // canNOT provide a value here (not integral) };
MyClass.cpp
const int MyClass::intvalue; // no value (already provided in header) const float MyClass::floatvalue = 0.07f; // value provided HERE
可以解决如上问题