错误:开关数量不是整数 [英] error: switch quantity not an integer
问题描述
我已经研究了我的问题在StackOverflow和多谷歌的链接,我仍然困惑。我认为最好的东西对我来说是问...
I have researched my issue all over StackOverflow and multi-google links, and I am still confused. I figured the best thing for me is ask...
我创建一个简单的命令行计算器。这里是我的代码到目前为止:
Im creating a simple command line calculator. Here is my code so far:
const std::string Calculator::SIN("sin");
const std::string Calculator::COS("cos");
const std::string Calculator::TAN("tan");
const std::string Calculator::LOG( "log" );
const std::string Calculator::LOG10( "log10" );
void Calculator::set_command( std::string cmd ) {
for(unsigned i = 0; i < cmd.length(); i++)
{
cmd[i] = tolower(cmd[i]);
}
command = cmd;
}
bool Calculator::is_legal_command() const {
switch(command)
{
case TAN:
case SIN:
case COS:
case LOG:
case LOG10:
return true;
break;
default:
return false;
break;
}
}
我得到的错误是: / p>
the error i get is:
Calculator.cpp: In member function 'bool Calculator::is_trig_command() const':
Calculator.cpp: error: switch quantity not an integer
Calculator.cpp: error: 'Calculator::TAN' cannot appear in a constant-expression
Calculator.cpp: error: 'Calculator::SIN' cannot appear in a constant-expression
Calculator.cpp: error: 'Calculator::COS' cannot appear in a constant-expression
强大的互联网,它说明字符串可以在switch语句中使用。
The mighty internet, it says strings are allowed to be used in switch statements.
感谢大家,感谢您的帮助。
Thanks everyone, I appreciate your help.
推荐答案
在切换
中,表达式必须是a 整合类型或类型类型,其中有明确的转换为整数类型(引用VS2008 docs )。
In switch
, the expression must be of "an integral type or of a class type for which there is an unambiguous conversion to integral type" (quoting VS2008 docs).
字符串类没有明确转换为整数类型,如 char
。
A string class doesn't have "unambiguous conversion to integral type", like a char
does.
解决方法:
-
创建
地图< string,int>
并打开地图的值:switch(command_map [command])
`
Create a
map<string, int>
and switch on the value of the map:switch(command_map[command])
`
执行如果
/ else
而不是switch。
Do a set of if
/else
instead of switch. Much more annoying and hard to read, so I'd recommend the map route.
另外,一个偶数对于真正复杂的逻辑,更好的解决方案是改进映射解决方案,以摆脱开关
完全,而是与一个函数查找: std :: map< std :: string,functionPointerType>
。它可能不需要您的特定情况,但是对于复杂的很长的查找逻辑更快。
As an aside, an even better solution for really complicated logic like that is to improve the mapping solution to get rid of switch
completely and instead go with a function lookup: std::map<std::string, functionPointerType>
. It may not be needed for your specific case, but is MUCH faster for complicated very long look-up logic.
这篇关于错误:开关数量不是整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!