In Fig. 6.10, we introduced enum
s. One problem with enum
s (also called unscoped enums) is that multiple enum
s may contain the same identifiers. Using such enum
s 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.
Error-Prevention Tip 6.5
Use scoped enums to avoid potential naming conflicts and logic errors from unscoped enums that contain the same identifiers.
3.135.187.210