Enumeration Types: Very useful. Make your program more reliable.

advertisement
Enumeration Types:
Very useful.
Can make your program easier to write and read.
Make your program more reliable.
They do this by bringing the programming language closer to the way you think
about the problem you are trying to program.
In programming we often encode things by integers. (By "encode" I mean taking
things we want to talk about and putting them into a form the computer
understands.)
The computer understands integers. They are efficient to represent on the
computer (in terms of bits) and computer operations on integers (such as +, -, <,
==, etc.) are efficient.
For readability, however, we don't want to work in terms of integers, we want to
work in terms of something more meaningful (e.g., clubs, spades, diamonds,
hearts; ace, jack, queen, king).
This is an example of the Labeling Principle:
"Avoid requiring someone to remember a list more than a few items long. Instead,
give the items meaningful names."
enum <name> { <value-0> , <value-1> , ... , <value-N> };
This encodes <value-0> as integer 0, <value-1> as 1, and so on, up to <value-N>
as N.
enum Suit { CLUBS, DIAMONDS, HEARTS, SPADES };
This encodes CLUBS as 0, DIAMONDS as 1, HEARTS as 2, and SPADES as 3.
Whenever you are using integers to encode something else (especially the elements
of some small set), you should probably use an enum.
enum Rank { ACE=1, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE,
TEN, JACK, QUEEN, KING };
We have in effect extended the C++ language with two new application-oriented
data types: Suit and Rank. We can have variables of these types, parameters of
these types, etc.
These would be most useful as part of a Card data type (structure).
I can use the Card structure to define other structures, like Deck (a deck of cards).
A Deck contains some number of Cards, which can be arranged in a vector (to keep
them in order).
There are several ways we could declare a "find" function to find a card in a deck.
E.g.,
find (c, d)
d.find(c)
c.find(d)
We could define it any of these ways, and it probably doesn't make much
difference. The only issue is which way is more natural to use.
The book does it the third way (which doesn't seem most natural to me).
This means find() is a member function of Cards.
int find (const Deck& d) const;
Remember that in C++ you always have to declare things before you use them. For
structures (or classes) that are defined in terms of each other, you have to use a
"forward declaration."
struct Deck;
struct Card { .... Deck .... };
struct Deck { .... Card .... };
Download