为什么我不能在switch-case语句中有一个变量? [英] Why can't I have a variable in switch-case statement?

查看:1057
本文介绍了为什么我不能在switch-case语句中有一个变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

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

在我的头文件中,我有:

In my header file I have:

protected:
    char up_key;
    char down_key;
    char right_key;
    char left_key;

我使用 Visual C ++ 2008。

推荐答案

错误消息状态,case表达式必须是常量。编译器在编译时将其构建为一个非常快的查找表,并且如果存在值可能随着程序运行而改变的可能性,则编译器不能这样做。

As the error message states, the case expressions must be constant. The compiler builds this as a very fast look-up table at compile time and it can't do that if there is a possibility that the values could change as the program runs.

如果你确实需要它们是可变的,而不是恒定的,你最好的选择是使用if / else语句。

If you do need them to be variable, not constant, your best bet is to use if/else statements instead.

这篇关于为什么我不能在switch-case语句中有一个变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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