为什么static const成员不能出现在常量表达式,如'switch' [英] Why static const members cannot appear in a constant expression like 'switch'

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

问题描述

我有以下声明一些静态const成员

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

有时候我想在开关中使用这些值like:

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

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

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

我已经读取其他开关不能出现常数并没有找到我的答案,因为我不知道为什么这些 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.

推荐答案

是因为

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

即可使用。

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

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