Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize a static const float in a C++ class in Visual Studio

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.

like image 270
mans Avatar asked Jul 10 '13 09:07

mans


2 Answers

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.

like image 150
gx_ Avatar answered Sep 22 '22 09:09

gx_


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;
like image 39
Daniel Daranas Avatar answered Sep 20 '22 09:09

Daniel Daranas