|
ex3-10.cpp - Example 3-10 Nested Classes |
// File: ex3-10.cpp - the card and deck example with nested classes
#include <iostream>
#include <cstdlib>
using namespace std;
const char* value_name[13] =
{"two","three","four","five","six",
"seven","eight","nine","ten","jack","queen","king","ace"};
const char* suit_name[4] =
{"clubs","diamonds","hearts","spades"};
class deck
{
public: // Why is this public?
class card
{
private:
int value;
int suit;
public:
void assign(int);
int get_value(void) const;
int get_suit(void) const;
void print(void) const;
};
private:
card d[52];
int next_card;
public:
void create_deck(void);
void shuffle(void);
void deal(int=5);
void print(void) const;
};
int deck::card::get_value(void) const {
return value;
}
int deck::card::get_suit(void) const {
return suit;
}
void deck::card::assign(int x)
{
value = x % 13;
suit = x / 13;
return;
}
void deck::card::print(void) const
{
cout << (value_name[get_value()]) << " of "
<< (suit_name[get_suit()]) << endl;
return;
}
void deck::create_deck(void)
{
for (int i = 0; i < 52; i++) d[i].assign(i);
next_card = 0;
return;
}
void deck::shuffle(void)
{
int i, k;
card temp;
cout << "I am shuffling the deck\n";
for (i = 0; i < 52; i++)
{
k = rand() % 52;
temp = d[i];
d[i] = d[k];
d[k] = temp;
}
return;
}
void deck::print(void) const
{
cout << "\nHere's the deck:\n";
for (int i = 0; i < 52; i++) d[i].print();
return;
}
void deck::deal(int no_of_cards)
{
cout <<"\nOk, I will deal you "<<no_of_cards<<" cards:\n";
for (int i=0;i<no_of_cards; i++) d[next_card++].print();
return;
}
int main (void)
{
// card C; // Instantiate a card object
deck::card C;
C.assign(17);
C.print(); // prints six of diamonds
deck poker;
poker.create_deck();
poker.print();
poker.shuffle();
poker.print();
poker.deal();
poker.deal(3);
return 0;
}
CIS27: Programming in C++ Instructor: Joe Bentley