Like Classes, Enumerations Define New Types
So long as the enum
is named, we can define and initialize objects of that type. An enum
object may be initialized or assigned only by one of its enumerators or by another object of the same enum
type:
open_modes om = 2; // error: 2 is not of type open_modesom = open_modes::input; // ok: input is an enumerator of open_modes
Objects or enumerators of an unscoped enumeration type are automatically converted to an integral type. As a result, they can be used where an integral value is required:
int i = color::red; // ok: unscoped enumerator implicitly converted to intint j = peppers::red; // error: scoped enumerations are not implicitly converted
Get C++ Primer, Fifth Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.