如何在开关语句中使用成员变量

How to use member variables in switch statements?

本文关键字:成员 变量 语句 开关      更新时间:2023-10-16

当我尝试在switch语句中使用成员变量作为大小时,程序无法编译

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 语句中使用成员变量?

C++开关是编译时构造,没有太多原因,它只是。因此,所有案例标签都必须是常量表达式,也称为编译时常量。

在您的示例中,val 只是不可变的,而不是常量表达式,因此存在错误。要修复它,您可以使用static conststatic constexpr

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

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