[英]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.