A
Alexander Hans
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;
};
While g++-3.2 is totally fine with this, g++-4.1.1 gives an error:
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
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
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;
};
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
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