Chapter 05 Compound Data Type - Constructed Type
1. Enumeration Type
- Type Construction
enum <enumeration-type-name> {<enumerration-value-list>};
Enumeration type name is an identifier, which identifies the name of an enumeration type, which can be left out.
Enumeration value list is a list of values separated by commas, and the values in it are integral symbolic constants, and each of them has a corresponding integer value which by default start from 0.
Enumeration variable definition:
<enumeration-type-name> <variable-list>; //or enum <enumeration-type-name> <variable-list>;
We can also define a enumeration type as well as defining a enumeration variable.
enum Day {SUN, MON, TUE, WED, THU, FRI, SAT} d1, d2, d3;
If we leave out the name of the enumeration type, we must define the variable just as we define the type or we’ll never have access to the type again because it’s anonymous.
-
Manipulation of Enumeration Type
-
Assignment
-
We can’t use assignment between variables of different enumeration types
-
If we assign an integer to a enumeration type variable, we assign the value in its value set corresponding to the integer. If there’s none, an error will be raised.
-
-
Comparison
- Compare the integer corresponding to it.
-
Output
- We can’t input a value to an enumeration variable
- But we can output an enumeration value in the form of its corresponding integer.
- So, if we want to input a enumeration value, there should be some special methods:
#include <iostream> using namespace std; enum Day {SUN, MON, TUE, WED, THU, FRI, SAT}; int main(){ Day d; int i; cin >> i; switch (i){ case 0: d = SUN; break; case 1: d = MON; break; case 2: d = TUE; break; case 3: d = WED; break; case 4: d = THU; break; case 5: d = FRI; break; case 6: d = SAT; break; default: cout << "Input Error!" << endl; return -1; } return 0; }
//another way if (i < 0 || i > 6){ cout << "Input Error!" << endl; return -1; } else d = (Day)i; //exeplicit type reversion
-