gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:20:47 25 4
gpt4 key购买 nike

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

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

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

}
};

gcc 给我这个错误:

use of ‘this’ in a constant expression

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

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

}
};

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

最佳答案

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

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

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

关于c++ - 如何在switch语句中使用成员变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48250035/

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