使用枚举而不是硬编码值
Using Enums instead of Hardcoded value
我有一些代码可以检测在QListWidget
中选择了哪个选项卡
int currentTab=ui->tabWidget->currentIndex();
if (currentTab==0)
{
// Code here
}
else if (currentTab==1)
{
// Code here
}
else if (currentTab==2)
{
// code here
}
else if (currentTab==3)
{
// code here
}
如何使用枚举代替if(currentTab==0)
或if(currentTab==1)
或if(currentTab==2)
或if(currentTab==3)
我会通过以下方式处理相同的问题(使用枚举类型(:
enum Tabs {
Tab1,
Tab2,
Tab3
};
void foo()
{
int currentTab = ui->tabWidget->currentIndex();
switch (currentTab) {
case Tab1:
// Handle the case
break;
case Tab2:
// Handle the case
break;
case Tab3:
// Handle the case
break;
default:
// Handle all the rest cases.
break;
}
}
使用下面给出的枚举的示例。
如果要在两个枚举中使用相同的枚举元素,则可以使用 enum 类(强类型枚举(C++11。
#include <iostream>
#include <cstdint>
using namespace std;
//enumeration with type and size
enum class employee_tab : std::int8_t {
first=0 /*default*/, second, third, last /*last tab*/
};
enum class employee_test : std::int16_t {
first=10 /*start value*/, second, third, last /*last tab*/
};
enum class employee_name : char {
first='F', middle='M', last='L'
};
int main(int argc, char** argv) {
//int currentTab=ui->tabWidget->currentIndex();
employee_tab currentTab = (employee_tab)1;
switch (currentTab) {
case employee_tab::first: //element with same name
cout << "First tab Selected" << endl;
break;
case employee_tab::second:
cout << "Second tab Selected" << endl;
break;
case employee_tab::third:
cout << "Third tab Selected" << endl;
break;
case employee_tab::last: //element with same name
cout << "Fourth tab Selected" << endl;
break;
}
employee_name currentName = (employee_name)'F';
switch (currentName) {
case employee_name::first: //element with same name
cout << "First Name Selected" << endl;
break;
case employee_name::middle:
cout << "Middle Name Selected" << endl;
break;
case employee_name::last: //element with same name
cout << "Last Name Selected" << endl;
break;
}
return 0;
}
输出:
第二个选项卡已选中
已选择的名字
相关文章:
- 为什么 int 类型的枚举类值不能用作 int
- 为什么static_cast基础类型的枚举类int8_t获得意外值?
- 如何使用默认值将枚举声明为 extern
- 将类用作类似枚举或具有特定值的类
- C++17:使用 std::optional 来评估枚举是否包含值
- 有没有办法使用类的私有枚举值作为模板参数?
- C++ 使用枚举类对象分配 std::map 值
- 如何使用默认值为构造函数中的枚举赋值?
- 用于获取枚举值的用户输入
- 使用 Doxygen 记录枚举类值,而不启用EXTRACT_ALL
- C++为类中的枚举项设置值
- 在结构中使用枚举的值
- 在运行时使用枚举器值作为模板函数的模板参数的元程序
- 枚举类上的运算符+,起始值不为零
- 如何设计运行时分配值枚举?
- 使用其他库中的值枚举
- C++单值枚举与预处理器指令
- 使用枚举而不是硬编码值
- 通过引用或值枚举类C++11
- 使用固定值枚举数的枚举零初始化