如何在开关语句中使用成员变量
How to use member variables in switch statements?
当我尝试在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 const
或static constexpr
class Foo
{
static const int val = 1; // this
static constexpr int val = 1; // or this
};
将其声明为 static const
。它不应该是一个变量(常量或非常量(,它应该是一个编译时常量。
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 内置函数可查看CPP中的成员变量
- 是否可以初始化不可复制类型的成员变量(或基类)
- 将包含C样式数组的对象初始化为成员变量(C++)
- 为什么我不能在一个类的不同行中声明和定义成员变量?
- 在循环中按顺序遍历成员变量
- c++类声明时,相同的例程,不同的成员变量类型
- 如何从另一个文件继承私有成员变量和公共函数
- 在C++类中,是否必须初始化作为数组的成员变量
- 如何从子成员函数修改父公共成员变量
- 我可以在 C++ 中将数据成员/变量从其定义之外添加到结构中吗?
- 从私有成员变量的成员方法返回unique_ptr
- 在派生类中使用基类的私有成员变量的最佳方法
- 静态 constexpr 类成员变量对多线程读取是否安全?
- C++:是否可以使用非静态成员变量模板?
- 打印所有继承的类成员变量和方法
- 如何在复杂继承中访问静态成员变量
- 为什么我不能在返回 const 的布尔函数中为类成员变量赋值?C++
- 成员变量与函数概念检查