【问题标题】:Using Enums instead of Hardcoded value使用枚举而不是硬编码值
【发布时间】:2016-02-15 10:08:51
【问题描述】:

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

【问题讨论】:

  • 为什么? currentIndex 是一个索引。
  • 您应该为此查看switch()。枚举只是让硬编码的值更容易理解。

标签: c++ qt enums


【解决方案1】:

我会用以下方式处理同样的事情(使用枚举类型):

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;
    }
}

【讨论】:

  • 当你描述case中所有可能的值时,编译器是否需要default?
  • 在某些情况下:您可以在其中添加Q_UNREACHABLE(),这样编译器会假定永远不会到达该位置。 (并且在调试模式下,如果确实如此,它将断言)
  • 这不是必需的,但在switch 语句中使用它是处理默认值和/或案例的好主意,在我的示例中为currentTab > 2。如果您错过它,一些编译器可能会报告警告。
【解决方案2】:

使用下面给出的枚举示例。
如果你想在两个枚举中使用相同的枚举元素,那么你可以使用enum classes (strongly typed enumerations) 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;
}

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

【讨论】:

    猜你喜欢
    • 2013-08-24
    • 1970-01-01
    • 2012-11-05
    • 1970-01-01
    • 2014-01-14
    • 1970-01-01
    • 2021-12-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多