Extending Enums: Exploring Base Enum Class Inheritance
In C , enums provide a convenient way to represent fixed sets of values. However, there may be scenarios where you want to inherit values from an existing enum class. This question explores the possibility of achieving such inheritance.
Can Enums Inherit Other Enums?
By default, enum types in C cannot inherit from other enums. However, we can leverage a class-based approach to simulate enum inheritance.
Class-Based Enum Inheritance
The following code demonstrates how to create a base and derived enum using classes:
<code class="cpp">#include <iostream> #include <ostream> class Enum { public: enum { One = 1, Two, Last }; }; class EnumDeriv : public Enum { public: enum { Three = Enum::Last, Four, Five }; }; int main() { std::cout << EnumDeriv::One << std::endl; std::cout << EnumDeriv::Four << std::endl; return 0; }</code>
In this example, the Enum class defines an enum with three values: One, Two, and Last. The EnumDeriv class inherits from Enum and extends it by adding three more values: Three, Four, and Five.
The enum values are scoped within the classes, allowing for the inheritance of values while maintaining name uniqueness. In this case, we can access EnumDeriv::One and EnumDeriv::Four without ambiguity.
Benefits of Class-Based Enum Inheritance
The above is the detailed content of Can C Enums Inherit from Other Enums?. For more information, please follow other related articles on the PHP Chinese website!