开发者

Can I put a cast operator in an enumeration to convert it to a different type?

For example, if I have:

enum SomeEnum { One, Two, Three };

and I want to be able to directly get the enumeration as an unsigned integer or a string, can I write a casting operator that would be capable of loo开发者_开发百科king at the enumerated value and returning a suitable representation for it?

I know you can do this with classes, but I wasn't sure if you could do it with enumerations.


Enumerations can be converted to an integer, you don't even need a cast to do so. There's no way to automatically convert it to a string however.

If you're willing to do a string array in parallel you can easily index it with your enumeration; the only problem is that it can get out of sync if you're not careful to modify both when you make a change.

char * SomeEnumNames[] = { "One", "Two", "Three" };

cout << SomeEnumNames[One] << endl; // should output "One"


No, this is not possible, you can only do that with classes. You'll need to write a function to turn an enumeration value to a string or whatever.

Note that enumeration values can be explicitly cast to ints though by themselves.


Yes, you can cast an enumeration to an integer type like this:

int someInt = (int)someEnumValue;

By default, the enumeration will start at 0 and increment for each value, unless you specifically set the integer value for each enumeration. You can assign the integer values to enumerations like this:

public enum SomeType
{
   FirstValue = 1,
   SecondValue = 3,
   ThirdValue = 5
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜