C++11—Scoped enums

Image

In Fig. 6.10, we introduced enums. One problem with enums (also called unscoped enums) is that multiple enums may contain the same identifiers. Using such enums in the same program can lead to naming collisions and logic errors. To eliminate these problems, C++11 introduces so-called scoped enums, which are declared with the keywords enum class (or the synonym enum struct). For example, we can define the Status enum of Fig. 6.10 as:

enum class Status { CONTINUE, WON, LOST };

To reference a scoped enum constant, you must qualify the constant with the scoped enum’s type name (Status) and the scope-resolution operator (::), as in Status::CONTINUE. This explicitly identifies CONTINUE as a constant in the scope of enum class Status. Thus, if another scoped enum contains the same identifier for one of its constants, it’s always clear which version of the constant is being used.


Image Error-Prevention Tip 6.5

Use scoped enums to avoid potential naming conflicts and logic errors from unscoped enums that contain the same identifiers.


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.89.47