我已经在StackOverflow和多个谷歌链接上研究了我的问题,但我仍然很困惑。我想对我来说最好的办法就是问...
我正在创建一个简单的命令行计算器。到目前为止,我的代码如下:
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;
}
}我得到的错误是:
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语句中使用。
谢谢大家,感谢你们的帮助。
发布于 2010-12-27 07:27:26
在switch中,表达式必须是“integral type类型或可以明确转换为整型的类类型”(quoting VS2008 docs)。
string类没有像char那样“明确地转换为整型”。
作为一种变通办法:
map<string, int>并打开映射的值:switch(command_map[command])‘if/else而不是开关。更烦人,更难读,所以我推荐地图路线。顺便说一句,对于这种真正复杂的逻辑,一个更好的解决方案是改进映射解决方案,完全摆脱switch,转而使用函数查找:std::map<std::string, functionPointerType>。对于您的特定情况,它可能不需要,但对于复杂的、非常长的查找逻辑,它的速度要快得多。
发布于 2010-12-27 08:03:53
正如其他人和编译器所评论的那样,switch不允许使用字符串。我只会使用if
bool Calculator::is_legal_command() const {
if(command == TAN) return true;
if(command == SIN) return true;
if(command == COS) return true;
if(command == LOG) return true;
if(command == LOG10) return true;
return false;
}我不认为这会更复杂,而且它已经是最快的了。你也可以使用我的switch macro,让它看起来像
bool Calculator::is_legal_command() const {
sswitch(command)
{
scase (TAN):
scase (SIN):
scase (COS):
scase (LOG):
scase (LOG10):
return true;
sdefault():
return false;
}
}(在return之后使用break是死代码,因此应该避免)。
发布于 2010-12-27 07:25:31
字符串不能在C++的switch语句中使用。您需要将其转换为if/else if,如下所示:
if (command == "tan")
{
// ...
}
else if (command == "cos")
{
// ...
}
// ...https://stackoverflow.com/questions/4535825
复制相似问题