ex4-4.cpp - Example 4-4 Constructor/Destructor - card and deck (1)

// File: ex4-4.cpp

#include <iostream>
#include <cstdlib>	// needed for rand() function
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 card
{
  private:
	 int value;
	 int suit;
  public:
	  card() {static int countvoid = 0;countvoid++;cout << "default ctor calls="<<countvoid<<endl;}
	 card(int);
	 int get_value(void) { return value;} 	// accessor function
	 int get_suit(void) { return suit;} 	// accessor function
	 void print(void);
};

card::card(int x)			// constructor
{static int countint = 0;countint++;cout << countint<<endl;
  value = x % 13;
  suit = x / 13;
}

void card::print(void)
{
  cout << (value_name[value]) << " of "
	 << (suit_name[suit]) << endl;
  return;
}


class deck
{
  private:
	 card d[52];
	 int next_card;
  public:
	 deck(void);
	 void shuffle(void);
	 void deal(int=5);
	 void print(void);
};

deck::deck(void)
{
  for (int i = 0; i < 52; i++) d[i] = card(i);
  next_card = 0;
}


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)
{
  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)
{
  deck poker;
  poker.shuffle();
  poker.print();
  poker.deal();
  poker.deal(3);
  return 0;
}



CIS27: Programming in C++    Instructor: Joe Bentley