p3-euchre
Enumerated Type
An enumerated type (enum
) represents a named set of values. For example, the suit of a playing card.
enum Suit {
SPADES = 0,
HEARTS = 1,
CLUBS = 2,
DIAMONDS = 3,
};
int main() {
Suit trump = CLUBS;
}
An enum
is represented by a number.
Suit trump = CLUBS;
cout << trump << endl; // 2
Operators like <
or ==
compare the numeric representation of an enum
.
Suit s1 = SPADES;
Suit s2 = DIAMONDS;
s1 < s2; // true
s1 == s2; // false
An enum
can be implicitly converted to an int
.
int suit_num = CLUBS; // CLUBS -> 2
An int
can be converted to an enum
with static_cast
.
Suit suit = static_cast<Suit>(2); // 2 -> CLUBS
Loop over an enum
starting at the first value and ending at the last. The numeric representation of the enum
must be in order.
for (int s = SPADES; s <= DIAMONDS; ++s) {
Suit suit = static_cast<Suit>(s);
}
Overloading the stream insertion operator (output) prints a string instead of the numeric representation.
std::ostream & operator<<(std::ostream &os, Suit suit) {
// logic for printing each Suit
}
int main() {
Suit trump = CLUBS;
cout << trump; // "Clubs"
}
Overloading the stream extraction operator (input) makes it easier to read an enum
from user input.
std::istream & operator>>(std::istream &is, Suit &suit) {
// logic for reading each Suit
}
int main() {
Suit suit;
cin >> suit; // user types "Clubs"
}