Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I initialize an in-class floating point constant?

Tags:

c++

visual-c++

I've recently run into Visual C++ 2005 failing to initialize in class constants, having run into the ubiquitous error

"error C2864: ... : only static const integral data members can be initialized within a class"

from code similar to

class MyClass:
{
private:
   static const double myConstant = 2.9768;
}

I've been able to figure out that non-integer types are the problem, and there are several ways to have integer constants, but I have not found a satisfactory work-around for defining constants scoped to a class. Is this type of declaration legal in later/other compilers?

like image 892
2NinerRomeo Avatar asked Jan 17 '26 04:01

2NinerRomeo


1 Answers

In C++03, you have to initialize non-integral static constants outside the class definition:

struct Foo
{
    static const double value;
};
const double Foo::value = 0.5;

In C++11, you can initialize arbitrary constexpressions from constant expressions inline:

struct Foo
{
    static constexpr double value = 0.5;
};

You may or may not still have to provide a definition for the variable, depending on whether you require it elsewhere in your code (e.g. by taking its address).

like image 90
Kerrek SB Avatar answered Jan 19 '26 20:01

Kerrek SB



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!