home *** CD-ROM | disk | FTP | other *** search
/ Beginning C++ Through Gam…rogramming (2nd Edition) / BCGP2E.ISO / source / chapter09 / friend_critter.cpp < prev    next >
Encoding:
C/C++ Source or Header  |  2006-10-21  |  1.3 KB  |  57 lines

  1. //Friend Critter
  2. //Demonstrates friend functions and operator overloading
  3.  
  4. #include <iostream>
  5. #include <string>
  6.  
  7. using namespace std;
  8.  
  9. class Critter
  10. {
  11.     //make following global functions friends of the Critter class
  12.     friend void Peek(const Critter& aCritter);
  13.     friend ostream& operator<<(ostream& os, const Critter& aCritter);
  14.     
  15. public:
  16.     Critter(const string& name = "");
  17.      
  18. private:
  19.     string m_Name;
  20. };
  21.  
  22. Critter::Critter(const string& name):
  23.     m_Name(name)
  24. {}
  25.  
  26. void Peek(const Critter& aCritter);
  27. ostream& operator<<(ostream& os, const Critter& aCritter);
  28.  
  29. int main()
  30. {
  31.     Critter crit("Poochie");
  32.  
  33.     cout << "Calling Peek() to access crit's private data member, m_Name: \n";
  34.     Peek(crit);
  35.     
  36.     cout << "\nSending crit object to cout with the << operator:\n";
  37.     cout << crit;
  38.     
  39.     return 0;
  40. }
  41.  
  42. //global friend function which can access all of a Critter object's members
  43. void Peek(const Critter& aCritter)
  44. {
  45.     cout << aCritter.m_Name << endl;
  46. }
  47.  
  48. //global friend function which can access all of Critter object's members
  49. //overloads the << operator so you can send a Critter object to cout
  50. ostream& operator<<(ostream& os, const Critter& aCritter)
  51. {
  52.     os << "Critter Object - ";
  53.     os << "m_Name: " << aCritter.m_Name;
  54.     return os;
  55. }
  56.  
  57.