转换c++中enum变量中的字符串变量

Convert a string variable in enum variable in c++

本文关键字:变量 字符串 enum c++ 转换      更新时间:2023-10-16

我需要你的帮助,请特别知道我可以在枚举变量转换字符串变量。

下面是我的代码:

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

我在test.cpp中有一个编译错误,如ST_DEL, ST_USEST_UNKNOWN没有声明。我在这里需要什么,以及如何在枚举类型中正确地使用字符串类型。谢谢你的帮助。

enum是数字常量(不是字符串),所以你不能写

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

还要注意每个枚举常量后面的逗号(不是分号)。

所以你应该写:

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

通常可以将枚举常量转换为对应的字符串:

    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" ;
        }
    }