使用枚举而不是硬编码值

Using Enums instead of Hardcoded value

本文关键字:编码值 枚举      更新时间:2023-10-16

我有一些代码可以检测在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;
}

输出:
第二个选项卡已选中
已选择的名字