error when declaring an enum to a variable
I have the following syntax:
enum home
{
no,
yes,
}homew;
home homes;
std::string s;
开发者_C百科s="no";
homes=s; //is not working. Why?
Were am I wrong?
You are confusing strings with enumerated values.
An enum
variable is simply an integer that you can use a literal for at compile time, nothing more than that.
It makes the code more understandable and self-documenting rather than merely using a number literal.
This
enum home { no, yes, } homew;
defines the type
home
plus a variablehomew
of that type.
Did you intent that? Why?The values defined for an
enum
type are literals, to be used as such:home homes = no;
In C++ there's no built-in way to convert between enum value literals and a string representation of them. If you need this, you'll have to cook up your own.
enums in C++ are implicitly an int
data type. You can't assign string values to enum.
It doesn't compile because C++ provides no built-in mechanism for converting from std::string
to an enum
.
typeof(home) != typeof(std::string) // types are not equal
Thus, you cannot assign an enum
to std::string
or otherwise. Implicit conversion between enum
and integral types like bool
, int
etc. is possible however.
Is there a way I can solve my problem as it is?
If possible use std::map
.
std::map<std::string, home> myTypes;
myTypes["yes"] = yes;
myTypes["no"] = no;
Now you can do,
homes = myTypes["no"];
As others pointed out, enums values are of int
type. You could instead write a small function that converts from enum to String
like this:
std::string GetStringFromEnum(home iHome)
{
switch (home)
{
case yes: return "yes";
case no: return "no"; break;
default: return "here be dragons";
}
}
and vice-versa:
home GetEnumFromString(std::string iImput)
{
if (iImput == "yes") return yes;
return no; //if you extend the enum beyond 2 values, this function will get more complicated
}
and you could modify your code like so:
homes = GetStringFromEnum(no)
the downside for this approach is that if you modify the enum, you must also modify the convert function.
HTH,
JP
精彩评论