Operator Overloading  «Prev

Overloading Stream Insertion Operator - Exercise

Overloading the operator <<

Objective: Overload the operator << so it outputs a playing card in a nicely formatted style.

Instructions

Here is another example of overloading <<. In this example, we define a playing card ADT.
Using the deck::pr_deck() function, and the overloaded pips and card output operators given below, overload the output operator for the deck class.

//card output.
#include  <iostream.h>

char  pips_symbol[14] = { '?', 'A', '2', '3', '4', 
  '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K' };
char  suit_symbol[4] = { 'c', 'd', 'h', 's' };

enum suit { clubs, diamonds, hearts, spades };

class pips {
public:
   void  assign(int n) { p = n % 13 + 1; }
   friend ostream& operator<<(ostream& out, pips x);
private:
   int  p;
};

class card {
public:
  suit  s;
  pips  p;
  void  assign(int n) 
    { cd = n; s = suit(n / 13); p.assign(n); }
  friend ostream& operator<<(ostream& out, card cd);
private:
  int  cd;       //a cd is from 0 to 51
};

class deck {
public:
   void  init_deck();
   void  shuffle();
   void  deal(int, int, card*);
   void  pr_deck();
private:
   card d[52];
};

Now let us overload these operators for the types card and pips:
ostream& operator<<(ostream& out, pips x){
   return (out << pips_symbol[x.p]);
}

ostream& operator<<(ostream& out, card cd)
{
   return (out << cd.p << suit_symbol[cd.s] << "  ");
}

void deck::pr_deck()
{
   for (int i = 0; i < 52; ++i) {
      if (i % 13 == 0)      //13 cards to a line
         cout << endl;
      cout << d[i]; 
   }
}

The functions that operate on pips, cards, and deck need to be friends of the corresponding class because they access private members.
The above code is available in a file named cards.cpp, which can be found in the compressed course download file available on the Resources page.
Paste your code below and click the Submit button when you are ready to submit this exercise.