简体   繁体   English

在C ++中的枚举变量中转换字符串变量

[英]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. 我在test.cpp中ST_UNKNOWN未声明ST_DELST_USEST_UNKNOWN的编译错误。 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用于数字常量(不是字符串),因此您不能编写

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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