c++ - 开关盒错误 |的值在常量表达式中不可用

标签 c++ c++11 switch-statement constants constexpr

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

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

我尝试使用 switch-case 比较它们,但我收到一个错误“'input1' 的值在常量表达式中不可用”。

#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();
    switch(result)
    {
        case input1:
            cout << "input1" << endl;
            break;
        case input2:
            cout << "input2" << endl;
            break;
    }
    return 0;
}

最佳答案

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

switch(result)
    {
        case 1:
            cout << "input1" << endl;
            break;
        case 2:
            cout << "input2" << endl;
            break;
    }

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

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

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

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

我建议将您的 switch 更改为 if 语句

if(input1)
{}
else if(intput2)
{}

下面的代码应该可以工作:

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

关于c++ - 开关盒错误 |的值在常量表达式中不可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46977678/

相关文章:

php - SWITCH语句有相同条件和不同条件的两种情况

java - Java ATM 项目中使用 If 语句进行切换

c++ - 在函数中找到 minExam

c++ - 多维数组中的 Operator[] 重载 C++

c++11 - 如何获取 C++ 的 Bazel 代码覆盖率摘要?

c++ - 泛化共享指针和 QSharedPointer::data() vs shared_ptr::get()?

c++ - C++ 中的静态鸭子类型(duck typing)

c - 为什么这些案件没有事先声明?

c++ - 非局部均值降噪算法在图像处理中的实现

c++ - 使用 std::inner_product 时内积为零