Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

An example Analysis of enum with scope of Category 11

Shulou Source: shulou.com Published: 2022-06-01 19:49:46 09月30日 Update

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!

Tags: Type function at the same time way analysis two content just method more knowledge problem different low-level practical effective confused tedious successful next Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno macOS Xiaomi Docker Shulou Information Linux