首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >错误:开关数量不是整数

错误:开关数量不是整数
EN

Stack Overflow用户
提问于 2010-12-27 07:21:07
回答 7查看 94.3K关注 0票数 15

我已经在StackOverflow和多个谷歌链接上研究了我的问题,但我仍然很困惑。我想对我来说最好的办法就是问...

我正在创建一个简单的命令行计算器。到目前为止,我的代码如下:

代码语言:javascript
复制
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;
    }

}

我得到的错误是:

代码语言:javascript
复制
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语句中使用。

谢谢大家,感谢你们的帮助。

EN

回答 7

Stack Overflow用户

回答已采纳

发布于 2010-12-27 07:27:26

switch中,表达式必须是“integral type类型或可以明确转换为整型的类类型”(quoting VS2008 docs)。

string类没有像char那样“明确地转换为整型”。

作为一种变通办法:

  1. 创建一个map<string, int>并打开映射的值:switch(command_map[command])
  2. 执行一组if/else而不是开关。更烦人,更难读,所以我推荐地图路线。

顺便说一句,对于这种真正复杂的逻辑,一个更好的解决方案是改进映射解决方案,完全摆脱switch,转而使用函数查找:std::map<std::string, functionPointerType>。对于您的特定情况,它可能不需要,但对于复杂的、非常长的查找逻辑,它的速度要快得多。

票数 25
EN

Stack Overflow用户

发布于 2010-12-27 08:03:53

正如其他人和编译器所评论的那样,switch不允许使用字符串。我只会使用if

代码语言:javascript
复制
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,让它看起来像

代码语言:javascript
复制
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是死代码,因此应该避免)。

票数 10
EN

Stack Overflow用户

发布于 2010-12-27 07:25:31

字符串不能在C++的switch语句中使用。您需要将其转换为if/else if,如下所示:

代码语言:javascript
复制
if (command == "tan")
{
    // ...
}
else if (command == "cos")
{
    // ...
}
// ...
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4535825

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档