An example Analysis of enum with scope of Category 11
This article introduces the relevant knowledge of "C++11 scoped enum example analysis". In the actual case operation process, many people will encounter such difficulties. Next, let Xiaobian lead you to learn how to deal with these situations! I hope you can read carefully and learn something!
Confusion of enumeration types
After the transition from C to C++, enumeration was widely used as a means of reducing program errors. But there is also a problem: duplication of enumeration values. Suppose we have the following definitions of the three primary colors:
The code also needs to define three primary colors:
When both are defined, a problem arises: red and blue are defined repeatedly.
the traditional solution
Changing the name of an enumeration value is certainly a method, but it is relatively low-level and we will not discuss it. It is common practice to place the definition of an enumeration type in a different scope (class or namespace). For example:
This way the two enumeration definitions do not conflict. You can use these two enumeration types in the following ways:
A little cumbersome, but effective enough.
C++11 solution
C++11 introduced the concept of scoped enumeration types. Its usage is as follows:
A comparison with the previous approach shows that only the class keyword has been added to the standard enumeration type definition format. The effect is to define a scope for the enumeration value with the same name as the enumeration type. After defining scoped enumeration types, you can use them in the following ways:
"C++11 scoped enum example analysis" content is introduced here, thank you for reading. If you want to know more about industry-related knowledge, you can pay attention to the website. Xiaobian will output more high-quality practical articles for everyone!