I have the following declaration of some static const members
.h
class MyClass : public MyBase
{
public:
static const unsigned char sInvalid;
static const unsigned char sOutside;
static const unsigned char sInside;
//(41 more ...)
}
.cpp
const unsigned char MyClass::sInvalid = 0;
const unsigned char MyClass::sOutside = 1;
const unsigned char MyClass::sInside = 2;
//and so on
At some point I want to use those value in a switch like :
unsigned char value;
...
switch(value) {
case MyClass::sInvalid : /*Do some ;*/ break;
case MyClass::sOutside : /*Do some ;*/ break;
...
}
But I get the following compiler error: error: ‘MyClass::sInvalid’ cannot appear in a constant-expression.
I have read other switch-cannot-appear-constant-stuff and didn’t find an answer for me since I don’t get why those static const unsigned char are not constant-expression.
I am using gcc 4.5.
The problems you see are due to the fact that this
cannot be a compile time constant expression, since the compiler doesn’t know its value. Initialize them in the header like this:
and it will work.