我写了一个简单的例子来解决我在写他的程序时遇到的问题。
在程序执行期间,当从函数返回值时,我得到了 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/