switch语句多字符常量

Jim*_*ang 5 c++ switch-statement

我正在尝试将其转换为switch语句

if (codeSection == 281)
    cout << "bigamy";
else if (codeSection == 321  ||  codeSection == 322)
    cout << "selling illegal lottery tickets";
else if (codeSection == 383)
    cout << "selling rancid butter";
else if (codeSection == 598)
    cout << "wounding a bird in a public cemetery";
else
    cout << "some other crime";

// Actual switch statement
switch (codeSection)
{
    case '281':
        cout << "bigamy" << endl;
        break;

    case '321':
    case '322':
        cout << "selling illegal lottery tickets" << endl;
        break;

    case '383':
        cout << "selling rancid butter" << endl;
        break;

    case '598':
        cout << "wounding a bird in a public cemetery";
        break;

    default:
        cout << "some other crime"<< endl;

}
Run Code Online (Sandbox Code Playgroud)

编译器说switch语句多字符常量,并给我一个黄色警告,但仍然编译.我的问题是假设只是以char形式?像案例'2'

vso*_*tco 5

case '281':
Run Code Online (Sandbox Code Playgroud)

应该

case 281:
Run Code Online (Sandbox Code Playgroud)

并且类似地对于其余部分,否则编译器"认为"您尝试使用多字符常量,这不是您可能想要的.

A case不一定是char.实际上,它必须是与转换和整体促销之后的条件类型相同类型的常量表达,例如参见http://en.cppreference.com/w/cpp/language/switch.