如何在switch语句中使用成员变量?

时间:2018-01-14 13:24:52

标签: c++ switch-statement

当我尝试在switch语句中使用成员varible作为 case 时,程序将无法编译

class Foo{
public:
    // outside the function
    const int val = 1;

    void bar(){
        switch (1){
            case val:
                // ...
                break;
            default:
                // ...
                break;
        }   

    }   
};

gcc给了我这个错误:

  

在常量表达式中使用'this'

但是当我将变量声明为局部变量时,它编译得很好

class Foo{
    public:
    void bar(){
        // inside the function
        const int val = 1;
        switch (1){
            case val:
                // ...
                break;
            default:
                // ...
                break;
        }   

    }   
};

为什么会发生这种情况?如何在switch语句中使用成员变量?

2 个答案:

答案 0 :(得分:3)

C ++开关是编译时构造,没有太多理由,它只是。因此,所有case标签必须是常量表达式,也就是编译时常量。

在您的示例中,val只是不可变的,而不是常量表达式,因此是错误。要解决此问题,您可以使用static conststatic constexpr

class Foo
{
    static const int val = 1;      // this
    static constexpr int val = 1;  // or this
};

答案 1 :(得分:2)

将其声明为static const。它不应该是一个变量(常量或不变),它应该是一个编译时常量。

相关问题