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?
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).
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