使用枚举而不是硬编码值

use*_*174 0 c++ enums qt

我有一些代码可以检测到哪个选项卡被选中 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
     }
Run Code Online (Sandbox Code Playgroud)

如何使用枚举代替if(currentTab==0)if(currentTab==1)if(currentTab==2)if(currentTab==3)

vah*_*cho 6

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

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 它不是必需的,但是在我的例子中当`currentTab> 2`时,在`switch`语句中使用它是处理默认值和/或情况的好主意.如果您错过了,某些编译器可以报告警告. (2认同)