简体   繁体   中英

Convert a string variable in enum variable in c++

I need your help please especially to know can I convert a string Variable in an enum variable.

Here is my code:

deco_fill.h

#include <iostream>
using namespace std;
#include <string.h>

class A{

class B{
    public:
    enum tStrict{
        "ST_UNKNOWN"=-1;
        "ST_USE"=0;
        "ST_DEL"=1;
    }

    public:
    tStrict mType;

    void setStrict(tStrict& newStrict ){
        return mType=newStrict;
    }
  }
}

test.h

#include <iostream>
using namespace std;
#include <string.h>
#include <deco_fill.h>

class C
{
   public:
    A::B::tStrict CnvStrToEnum(const string& str); //This method will return   a     tStrict type

}

test.cpp

#include <iostream>
using namespace std;
#include <string.h>
#include <test.h>
#include <deco_fill.h>


A::B::tStrict C::CnvStrToEnum(const string& str)
{
   if (str=="ST_USE")
      return ST_USE;
   else if (str=="ST_DEL")
      return ST_DEL;
   else
      return ST_UNKNOWN;
 }

test_set.cpp

#include <iostream>
using namespace std;
#include <string.h>
#include <deco_fill.h>
#include <test.h>

string st=ST_USE;
A::B::tStrict strictType=CnvStrToEnum(st);


setStrict(strictType);//I want here to use the setStrict methode to set a new variable of type enum with that. This part is not important

I have a compile error in test.cpp like ST_DEL , ST_USE and ST_UNKNOWN were not declared. What's do I need here and how can I correctly the string type in my enum type. Thanks for your help.

enum is for numeric constants (not strings), so you can't write

enum tStrict{
    "ST_UNKNOWN"=-1; 
    "ST_USE"=0;
    "ST_DEL"=1;
}

Also note it's comma (NOT semicolon) after each enum constant.

So instead you should write:

enum tStrict{
    ST_UNKNOWN=-1,
    ST_USE,
    ST_DEL
};

Usually you can then convert enum constants to string counterparts:

    const char *tStrictStr( const enum tStrict t )
    {
        switch( t )
        {
            case ST_UNKNOWN : return "ST_UNKNOWN" ;
            case ST_USE     : return "ST_USE"     ;
            case ST_DEL     : return "ST_DEL"     ;
            default         : return "ST_UNKNOWN" ;
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM