gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 21:39:14 24 4
gpt4 key购买 nike

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

.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

有时我想在开关中使用这些值,例如:

unsigned char value;
...
switch(value) {
case MyClass::sInvalid : /*Do some ;*/ break;
case MyClass::sOutside : /*Do some ;*/ break;
...
}

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

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

我使用的是 gcc 4.5。

最佳答案

你看到的问题是因为这个

static const unsigned char sInvalid;

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

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

它会起作用的。

关于c++ - 为什么静态常量成员不能出现在像 'switch' 这样的常量表达式中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10619129/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com