Ken*_*Ken 10 c++ string switch-statement constant-expression
我已经在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;
}
}
Run Code Online (Sandbox Code Playgroud)
我得到的错误是:
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
Run Code Online (Sandbox Code Playgroud)
强大的互联网,它表示允许在switch语句中使用字符串.
谢谢大家,感谢您的帮助.
DVK*_*DVK 19
在switch,表达式必须是" 整数类型或类型类型,其中有明确的转换为整数类型"(引用VS2008文档).
字符串类没有"明确转换为整数类型",就像一个char.
作为一种解决方法:
创建一个map<string, int>并打开地图的值:switch(command_map[command])
`
做一组if/ else而不是开关.更烦人,更难读,所以我推荐地图路线.
顺便说一句,对于真正复杂的逻辑来说,更好的解决方案是改进映射解决方案以switch完全摆脱,而不是使用函数查找:std::map<std::string, functionPointerType>.对于您的特定情况可能不需要它,但对于复杂的非常长的查找逻辑来说,速度要快得多.
正如其他人和编译器所评论的那样,不允许使用字符串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;
}
Run Code Online (Sandbox Code Playgroud)
我不认为这更复杂,而且它的速度和它一样快.您也可以使用我的开关宏,使其看起来像
bool Calculator::is_legal_command() const {
sswitch(command)
{
scase (TAN):
scase (SIN):
scase (COS):
scase (LOG):
scase (LOG10):
return true;
sdefault():
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
(break在return死代码之后,应该避免).
| 归档时间: |
|
| 查看次数: |
66332 次 |
| 最近记录: |