Assigning values to enumerated types
enum options {Yes,No};
class A{
int i;
string str;
options opt;
};
int main{
A obj;
obj.i=5;
obj.s开发者_JS百科tr="fine";
obj.opt="Yes"; // compiler error
}
How can assign const char *
to opt?
Just do
obj.opt=Yes;
This code:
obj.opt="Yes";
attempts to assign a string literal (a completely different type) to an enum type, which C++ doesn't automagically convert for you.
How can assign const char * to opt?
You'll have to do this manually, I like to keep a set of free functions around for doing conversions like this with my enums, ie I'll wrap my enums in a namespace and provide some functions for working with them:
namespace options
{
enum Enum {Yes,No,Invalid};
Enum FromString(const std::string& str);
// might also add ToString, ToInt, FromInt to help with conversions
}
Enum FromString(const std::string& str)
{
if (str == "Yes")
{
return Yes
}
else if (str == "No")
{
return No;
}
return Invalid; //optionally throw exception
}
Now you can do:
class A{
int i;
string str;
options::Enum opt; // notice change here
};
...
obj.opt=options::FromString("Yes");
So you can see, enums in C++ probably don't give you all the bells and whistles of enums in other languages. You'll have to manually convert things yourself.
Enums are not strings, but just values
obj.opt = Yes;
Because an enum value is not a string. This is correct :
int main{
A obj;
obj.opt=Yes;
}
You can't do this. You will have to use some string comparisons and set it.
In your case you can "convert" enum to const char*
. All what you need is to create macro.
For example:
#define ENUM_TO_CSTR(x) #x
and then:
obj.opt=ENUM_TO_CSTR(Yes)
.
This macro will convert everything you pass to it into C-like string. It won't convert variable value, but only its name!
int x = 10; cout << ENUM_TO_CSTR(x) << endl;
Will print x
(not 10
) on screen, so be careful using it!
When you try to assign "Yes" it means that you are trying to assign a string value and not the enum constant from the enum options. Instead use the syntax:
obj.opt = Yes;
Try printing the value of opt from obj:
cout << obj.opt;
You will get the output as 0, since enum indices start from 0. Yes is 0 and No is 1.
精彩评论