I have a code like this:
class MyClass
{
private:
static const int intvalue= 50;
static const float floatvalue = 0.07f;
};
in Visual studio 2010 and I am getting this error:
Myclasses.h(86): error C2864: 'MyClass::floatvalue : only static const integral data members can be initialized within a class
So how to initialize a static constant float in c++?
If I use constructor, every time that an object of this class is created, the variable is initialized which is not good.
apparently the code is compiled with GCC on Linux.
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
Also, concerning
apparently the code is compiled with GCC on Linux.
This is due to an extension. Try with flags like -std=c++98
(or -std=c++03
, or -std=c++11
if your version is recent enough) and -pedantic
and you will (correctly) get an error.
Try the following.
In the header file, instead of your current statement write:
static const float floatvalue;
In the CPP file, write:
const float MyClass::floatvalue = 0.07f;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With