我有这样的代码:
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 ++中初始化静态常量float?
如果我使用构造函数,每次创建此类的对象时,该变量都被初始化,这是不好的。
显然代码是在Linux上使用GCC编译的。
答案 0 :(得分:12)
<强> 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
,您将(正确地)收到错误。
答案 1 :(得分:1)
请尝试以下操作。
在头文件中,而不是当前的语句写:
static const float floatvalue;
在CPP文件中,写下:
const float MyClass::floatvalue = 0.07f;
答案 2 :(得分:0)
您必须在课堂外定义它们,如下所示:
const int MyClass::intvalue = 50;
const float MyClass::floatvalue = 0.07f;
当然,这不应该在标题中完成,否则会出现多实例错误。使用int
s,您可以使用enum {intvalue = 50};
伪造它们,但这不适用于浮点数。