Enum
- #include <iostream>
-
- enum Day {Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday};
-
- int main(int argc, char *argv[])
- {
- for(int i = Monday; i <= Sunday; i++)
- std::cout<<static_cast<Day>(i)<<std::endl;
-
- for(Day d = Monday; d <= Sunday; d = static_cast<Day>(d+1))
- std::cout<<d<<std::endl;
-
- return 0;
- }
-
- Cast integer to Day, static_cast<Day>(3)
- Cast Day to integer, int i = Thursday
- Math operation, day2 = static_cast<Day>(day1+1);
- ++ operator cannot be used with an enum variable
Specify Integer Value for Enumerators
- #include <iostream>
-
- enum Day {Monday = 1, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday};
-
- int main(int argc, char *argv[])
- {
- for(int i = Monday; i <= Sunday; i++)
- std::cout<<static_cast<Day>(i)<<std::endl;
-
- return 0;
- }
-
- An enumerator name can't be used in multiple enumerations within the same namespace
- Define the enumeration in a header, #include that header wherever needed if the enumeration is needed in mmultiple files
Compare Enumerator Values
- #include <iostream>
-
- enum Day {Monday = 1, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday};
-
- int main(int argc, char *argv[])
- {
- if(1 == Monday)
- std::cout<<"Compare integer with Day ..."<<std::endl;
-
- if (Monday < Thursday)
- std::cout<<"Monday is earlier than Thursday ..."<<std::endl;
-
- return 0;
- }
-
Enum ClassC++11
- #include <iostream>
-
- int main(int argc, char *argv[])
- {
- enum Color {Blue, Red};
- enum Fruit {Banana, Orange};
-
- //enum types are implicitly converted to integer, then they are compared
- if (Blue == Banana)
- std::cout<<"Blue equals to Banana ..."<<std::endl;
-
- return 0;
- }
-
- #include <iostream>
-
- int main(int argc, char *argv[])
- {
- enum class Color {Blue, Red};
- enum class Fruit {Banana, Orange};
-
- //enum class types are not implicitly converted to integer
- //if (Color::Blue == Fruit::Banana)//compile error
- //std::cout<<"Blue equals to Banana ..."<<std::endl;
- Color c = Color::Blue;
- Fruit f = Fruit::Banana;
-
- std::cout<<static_cast<int>(c)<<std::endl;
- std::cout<<static_cast<int>(f)<<std::endl;
-
- return 0;
- }
-
- enum type will be implicitly converted to integer
- enum class type will not be implicitly converted to integer
Reference