如何在Visual Studio中初始化C++类中的静态常量浮点值
How to initialize a static const float in a C++ class in Visual Studio
我有一个这样的代码:
class MyClass
{
private:
static const int intvalue= 50;
static const float floatvalue = 0.07f;
};
在Visual studio 2010中,我得到了这个错误:
Myclasses.h(86): error C2864: 'MyClass::floatvalue : only static const integral data members can be initialized within a class
那么,如何在c++中初始化静态常量浮点呢?
如果我使用构造函数,那么每次创建此类的对象时,都会初始化变量,这是不好的。
显然,代码是在Linux上使用GCC编译的。
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
此外,关于
显然,代码是在Linux上使用GCC编译的。
这是由于延期。尝试使用-std=c++98
(或-std=c++03
,或-std=c++11
,如果您的版本足够新)和-pedantic
等标志,您将(正确地)得到错误。
尝试以下操作。
在头文件中,代替您当前的语句写:
static const float floatvalue;
在CPP文件中,写入:
const float MyClass::floatvalue = 0.07f;
您必须在类之外定义它们,如下所示:
const int MyClass::intvalue = 50;
const float MyClass::floatvalue = 0.07f;
当然,这不应该在头中完成,否则会出现多实例错误。对于int
,您可以使用enum {intvalue = 50};
来伪造它们,但这在浮点运算中不起作用。
相关文章:
- 私有类型的静态常量成员
- 分离一个静态常量 std::thread?
- 从另一个静态常量数组初始化静态常量数组(只需少量计算)
- 我可以在运行时重新定义在 OpenCascade/OCCT 标头中定义的 c++ 静态常量吗?
- 如何为静态常量模板化专用整数值分配存储
- 使用什么代替"静态常量 TCHAR *"
- C++ 模板中的静态常量初始化顺序
- 如何在编译时解析静态常量 std::string?
- 关于静态常量数据模因的声明和定义的混淆
- 将 static_cast<int>(-15) 分配给静态常量字符类型变量
- 为什么在第二类中使用静态常量会在第一类中给出编译器错误?
- 静态常量与常量局部变量,哪一个性能更好
- 如何在模板类中设置静态常量变量
- public:静态常量字符串声明/初始化问题
- 有没有办法声明一个公共静态常量,该常量将使用 constexpr 在源文件中定义(有什么区别)?
- 对静态常量积分类型的未定义引用
- 全局变量中的静态常量与常量
- c++ 类中的静态常量变量和常量变量在存储方面是否有区别
- 避免在静态常量类上定义但不使用
- 指向静态常量对象的共享指针?