【发布时间】:2012-01-19 04:03:25
【问题描述】:
这是我的代码:
bool Character::keyPress(char c)
{
switch(c)
{
case up_key:
move(0, -1);
break;
case down_key:
move(0, 1);
break;
case left_key:
move(-1, 0);
break;
case right_key:
move(1,0);
break;
default:
return false;
}
return true;
}
编译器抱怨:
error C2051: case expression not constant
error C2051: case expression not constant
error C2051: case expression not constant
error C2051: case expression not constant
在我的头文件中:
protected:
char up_key;
char down_key;
char right_key;
char left_key;
我正在使用Visual C++ 2008。
【问题讨论】:
-
switch case 表达式必须是编译时常量。将它们更改为
static const char up_key = 1;等,问题就解决了。 -
因为标准是这样说的。这是旧时代的残余,
switch被引入作为“更好”的演示文稿,它被自动转换为数组查找(因此需要常量)。现在它已经不太有意义了,但是语法没有改变所以......
标签: c++ switch-statement