switch/case statement in C++ with a QString type

后端 未结 14 1903
南笙
南笙 2020-12-16 10:19

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

switch expression of type \'QString\' is illegal

How can I us

相关标签:
14条回答
  • 2020-12-16 10:35

    This seems a little saner IMHO.

    bool isStopWord( QString w ) {
        return (
            w == "the" ||
            w == "at" ||
            w == "in" ||
            w == "your" ||
            w == "near" ||
            w == "all" ||
            w == "this"
        );
    }
    
    0 讨论(0)
  • 2020-12-16 10:37

    This has nothing to do with Qt, just as it has nothing to do with the colour of your socks.

    C++ switch syntax is as follows:

    char c = getc();
    switch( c ) {
    case 'a':
        a();
        break;
    case 'b':
        b();
        break;
    default:
        neither();
    }
    

    If that doesn't help then please list in detail the error message, possible along with the colour of you socks.

    Edit: to respond to your reply, you can't use switch with none-integral types. In particular, you can't use class types. Not objects of type QString and not objects of any other type. You can use an if-else if-else construct instead, or you can use runtime or compile time polymorphism, or overloading, or any of the array of alternatives to a switch.

    0 讨论(0)
  • 2020-12-16 10:38

    It is identical to a C++ switch statement.

    switch(var){
      case(option1):
          doesStuff();
          break;
      case(option2):
         etc();
         break;
    }
    
    0 讨论(0)
  • 2020-12-16 10:41

    How can I use the switch statement with a QString?

    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.

    0 讨论(0)
  • 2020-12-16 10:43

    You can, creating an QStringList before iteration, like this:

    QStringList myOptions;
    myOptions << "goLogin" << "goAway" << "goRegister";
    
    /*
    goLogin = 0
    goAway = 1
    goRegister = 2
    */
    

    Then:

    switch(myOptions.indexOf("goRegister")){
      case 0:
        // go to login...
        break;
    
      case 1:
        // go away...
        break;
    
      case 2:
        //Go to Register...
        break;
    
      default:
        ...
        break;
    }
    
    0 讨论(0)
  • 2020-12-16 10:46

    I would suggest to use if and break. This would make it near to switch case in the computation.

    QString a="one"
    if (a.contains("one"))
    {
    
       break;
    }
    if (a.contains("two"))
    {
    
       break;
    }
    
    0 讨论(0)
提交回复
热议问题