The enumerated values in C ++ are converted to Integers and strings.

Source: Internet
Author: User

Enumeration type in C ++
C ++ 11 provides a safer Enumeration type and cannot be used directly as an integer. But what if we want to use it as an integer?
For example
Enum class ElemType
{
CAP,
IND,
VS
};

In the past, when we used the enumeration type, we did not add the class keyword, which can be defined as follows,
Enum ElemTypeOld
{
CAP = 1,
IND,
VS = 3
};
After defining an enumerated variable, you can directly compare it with an integer. However, there are some problems in this process, because the custom integer values may not be consecutive, and some are defined, and others are not defined.
When ElemTypeOld: IND is output, 2 is output. If the CAP value is changed to 2, the IND value is 3, which is the same as the VS value. (This is also the case when ElemType does the same. This is not the case if the type is safer .)

In ElemTypeOld, whether or not an integer is specified, it can be used as an integer. In ElemType, it can only be used as an enumeration type and cannot be mixed with an integer. C ++ also provides the method to convert it to an integer,
Static_cast <int> (ElemType: CAP)-> 0,
If an integer is specified in ElemType, the specified integer is obtained.

I originally wanted to convert the enumerated type into string output, but encountered the above problem when converting it into an integer. Next, go to the topic.
One way is to use the swicth statement,
String getElemTypeName (ElemType type)
{
Switch (type)
{
Case ElemType: CAP: return "CAP"; break;
Case ElemType: IND: return "IND"; break;
Case ElemType: VS: return "VS"; break;
Default: return "error"; break;
}
}
Another method is to define a constant string array,
Const char * names [] = {"CAP", "IND", ""};
String getElemTypeName (ElemType type)
{
Int idx = static_cast <int> (type );
Return names [idx];
}

There are other ways to use macro definition on the Internet. I think these two methods are enough.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.