带有 QString 类型的 C++ 中的 switch/case 语句

2022-01-19 00:00:00 qt4 qt switch-statement c++ qstring

我想在我的程序中使用 switch-case,但是编译器给了我这个错误:

I want to use switch-case in my program but the compiler gives me this error:

switch expression of type 'QString' is illegal

如何将 switch 语句与 QString 一起使用?

How can I use the switch statement with a QString?

我的代码如下:

bool isStopWord( QString word )
{
bool flag = false ;

switch( word )
{
case "the":
    flag = true ;
    break ;
case "at" :
    flag = true ;
    break ;
case "in" :
    flag = true ;
    break ;
case "your":
    flag = true ;
    break ;
case "near":
    flag = true ;
    break ;
case "all":
    flag = true ;
    break ;
case "this":
    flag = true ;
    break ;
}

return flag ;
}

推荐答案

如何在 QString 中使用 switch 语句?

How can I use the switch statement with a QString?

你不能.在 C++ 语言中,switch 语句只能与整数或枚举类型一起使用.您可以将类类型的对象正式放入 switch 语句中,但这仅意味着编译器将寻找用户定义的转换以将其转换为整数或枚举类型.

You can't. In C++ language switch statement can only be used with integral or enum types. You can formally put an object of class type into a switch statement, but that simply means that the compiler will look for a user-defined conversion to convert it to integral or enum type.

相关文章