为什么静态常量成员不能出现在像'switch'这样的常量表达式中 [英] Why static const members cannot appear in a constant expression like 'switch'

查看:37
本文介绍了为什么静态常量成员不能出现在像'switch'这样的常量表达式中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

它会起作用的.

这篇关于为什么静态常量成员不能出现在像'switch'这样的常量表达式中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆