[英]Convert a string variable in enum variable in c++
我需要您的帮助,尤其是要知道我可以在枚举变量中转换字符串变量。
这是我的代码:
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_UNKNOWN
未声明ST_DEL
, ST_USE
和ST_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" ;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.