On Sep 6, 7:53 am, Barry <dhb2...@gmail.com> wrote:
> Alexander Hans wrote:
> > Hi,
>
> > what's the usual way in C++ to define a static constant class member?
> > Consider the following example:
>
> > class TestClass
> > {
> > public:
> > static const double a = 12.5;
> > static const double b = 2 * a;
>
> only integral type can't be initialized inside of class declaration.
>
>
>
>
>
> > };
>
> > While g++-3.2 is totally fine with this, g++-4.1.1 gives an error:
>
> >> test.cpp:5: error: 'TestClass::a' cannot appear in a constant-expression
>
> > I can't see where's the problem here. TestClass::a is declared as being
> > constant and so is TestClass::b. I know that another possible way (that
> > also g++-4.1.1 accepts) is to initialize the values outside the class
> > definition:
>
> > class TestClass
> > {
> > public:
> > static const double a;
> > static const double b;
> > };
>
> > const double TestClass::a = 12.5;
> > const double TestClass::b = 2 * TestClass::a;
>
> > However, I shouldn't put the last two lines into a header file if it is
> > included by more than one .cpp implementation files if the resulting object
>
> you need to place them in a cxx file.
>
> > files are supposed to be linked afterwards, since there will be multiple
> > initializations then, no matter if they are the same or not. Putting the
> > initialization into one specific implementation file, everything will work,
> > but I would like to have the initialization within the header file.
>
> > Anyhow, I'm most interested in an explanation of the reason why g++-4.1.1 is
> > telling me why TestClass::a can't appear in a constant-expression.
>
> > Best regards,
>
> > Alex
>
> --
> Thanks
> Barry- Hide quoted text -
>
> - Show quoted text -
I think Barry meant to say only integral types CAN be initialized
inside a class declaration. This includes char, short, int, long int,
long long and enum types. It does _NOT_ include float, double or long
double.