为什么静态常量成员不能出现在像'switch'这样的常量表达式中

2022-01-19 00:00:00 gcc constants switch-statement c++

我有一些静态常量成员的以下声明

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;
    ...
}

但我得到以下编译器错误:错误:'MyClass::sInvalid' 不能出现在常量表达式中.

But I get the following compiler error: error: 'MyClass::sInvalid' cannot appear in a constant-expression.

我已阅读其他 switch-cannot-appear-constant-stuff 并没有为我找到答案,因为我不明白为什么那些 static const unsigned char 不是常量表达式.

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.

我使用的是 gcc 4.5.

I am using gcc 4.5.

推荐答案

你看到的问题是因为这个

The problems you see are due to the fact that this

static const unsigned char sInvalid;

不能是编译时常量表达式,因为编译器不知道它的值.像这样在标题中初始化它们:

cannot be a compile time constant expression, since the compiler doesn't know its value. Initialize them in the header like this:

class MyClass : public MyBase
{
public:
    static const unsigned char sInvalid = 0;
    ...

它会起作用的.

相关文章