Barbara Ericson, Allen B. Downey, Jason L. Wright (Editor)
Section13.1Enumerated types
In the previous chapter I talked about mappings between real-world values like rank and suit, and internal representations like integers and strings. Although we created a mapping between ranks and integers, and between suits and integers, I pointed out that the mapping itself does not appear as part of the program.
Actually, C++ provides a feature called an enumerated type that makes it possible to (1) include a mapping as part of the program, and (2) define the set of values that make up the mapping. For example, here is the definition of the enumerated types Suit and Rank:
The definition of Rank overrides the default mapping and specifies that ACE should be represented by the integer 1. The other values follow in the usual way.
Once we have defined these types, we can use them anywhere. For example, the instance variables rank and suit are can be declared with type Rank and Suit:
Listing13.1.1.This active code uses the enumerated types created above to construct Card objects. Feel free to modify the values that the cards are being initialized to in the constructor: this will change the output from the print function. Notice how this is much clearer than using integers.
Because we know that the values in the enumerated types are represented as integers, we can use them as indices for a vector. Therefore the old print function will work without modification. We have to make some changes in buildDeck, though:
In some ways, using enumerated types makes this code more readable, but there is one complication. Strictly speaking, we are not allowed to do arithmetic with enumerated types, so suit++ is not legal. On the other hand, in the expression suit+1, C++ automatically converts the enumerated type to integer. Then we can take the result and typecast it back to the enumerated type:
enumScoops{ SINGLE =1, DOUBLE, TRIPLE };enumFlavor{ VANILLA, CHOCOLATE, STRAWBERRY, COOKIESNCREAM, MINTCHIP, COOKIEDOUGH };enumOrder{ CUP, CAKECONE, SUGARCONE, WAFFLECONE }structiceCream{
Scoops scoops;
Flavor flavor;
Order order;iceCream(Scoops s, Flavor f, Order o);printOrder(){// To save space, I didn't include the mapping.// I'm sure you can still figure it out.
cout <<"Who ordered a "<< scoops[scoop]<<" scoop of "<< flavors[flavor]<<" in a "<< orders[order]<<?;}};intmain(){
iceCream icecream(2,3,2);
iceCream.printOrder();}
Who ordered a triple scoop of Cookies ’n’ Cream in a sugar cone?