开关盒错误 | 的值不可用于常量表达式

Евг*_*кин 6 c++ constants switch-statement constexpr c++11

我写了一个简单的例子来解决我在写他的程序时遇到的问题。

\n\n

在程序执行期间,当从函数返回值时,我得到 input1 和 input2 的值,这些值永远不会改变。然后稍后,在程序过程中进行各种计算后,我得到一个结果,该结果也不再可变。

\n\n

我正在尝试使用 switch-case 来比较它们,但出现一个错误“\xe2\x80\x98input1\xe2\x80\x99 的值在常量表达式中不可用”。

\n\n
#include <iostream>\n\nusing namespace std;\n\nchar getChar()\n{\n    char c;\n    cin >> c;\n    return c;\n}\n\nint main()\n{\n    // it doesn\'t work\n    const char input1 = getChar();\n    const char input2 = getChar();\n\n    // it it works\n    //const char input1 = \'R\';\n    //const char input2 = \'X\';\n\n    char result = getChar();\n    switch(result)\n    {\n        case input1:\n            cout << "input1" << endl;\n            break;\n        case input2:\n            cout << "input2" << endl;\n            break;\n    }\n    return 0;\n}\n
Run Code Online (Sandbox Code Playgroud)\n

GPP*_*PPK 2

您必须在编译时知道您的 case 语句。IE

switch(result)
    {
        case 1:
            cout << "input1" << endl;
            break;
        case 2:
            cout << "input2" << endl;
            break;
    }
Run Code Online (Sandbox Code Playgroud)

这些行虽然 const 仅真正意味着只读,并且不会在编译时初始化。

// it doesn't work
const char input1 = getChar();
const char input2 = getChar();
Run Code Online (Sandbox Code Playgroud)

以下两行之所以有效,是因为编译器只是在代码运行之前将 X & R 替换为 switch 语句

// it it works
//const char input1 = 'R';
//const char input2 = 'X';
Run Code Online (Sandbox Code Playgroud)

我建议将 switch 更改为 if 语句

if(input1)
{}
else if(intput2)
{}
Run Code Online (Sandbox Code Playgroud)

以下代码应该可以工作:

#include <iostream>

using namespace std;

char getChar()
{
    char c;
    cin >> c;
    return c;
}

int main()
{
    // it doesn't work
    const char input1 = getChar();
    const char input2 = getChar();

    // it it works
    //const char input1 = 'R';
    //const char input2 = 'X';

    char result = getChar();
    if(result == input1){
            cout << "input1" << endl;
    }
    else if(result == input2){
            cout << "input2" << endl;
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)