Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 15th, 2012  |  syntax: None  |  size: 1.32 KB  |  hits: 12  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Overloading operator<< for printing as a member
  2. class TestClass {
  3. public:
  4.     ostream& operator<<(ostream& os) {
  5.         return os << "I'm in the class, msg=" << msg << endl;
  6.     }
  7.  
  8. private:
  9.     string msg;
  10. };
  11.  
  12.  
  13. int main(int argc, char** argv) {
  14.     TestClass obj = TestClass();
  15.     cout << obj;
  16.  
  17.     return 0;
  18. }
  19.        
  20. ostream& operator<<(ostream& os, TestClass& obj) {
  21.     return os << "I'm outside of the class and can't access msg" << endl;
  22. }
  23.        
  24. class TestClass {
  25. public:
  26.     friend ostream& operator<<(ostream& os, TestClass const & tc) {
  27.         return os << "I'm a friend of the class, msg=" << tc.msg << endl;
  28.     }
  29.  
  30. private:
  31.     string msg;
  32. };
  33.        
  34. class TestClass {
  35. public:
  36.     ostream& print(ostream& os) const {
  37.         return os << "I'm in the class, msg=" << msg << endl;
  38.     }
  39.  
  40. private:
  41.     string msg;
  42. };
  43.  
  44.  
  45. ostream& operator<<(ostream& os, TestClass& obj) {
  46.     return obj.print(os);
  47. }
  48.  
  49. int main(int argc, char** argv) {
  50.     TestClass obj;
  51.     cout << obj;
  52.  
  53.     return 0;
  54. }
  55.        
  56. class TestClass
  57. {
  58. public:
  59.     // Have a nice friend.
  60.     // This tightly binds this operator to the class.
  61.     // But that is not a problem as in reality it is already tightly bound.
  62.     friend ostream& operator<<(ostream& os, TestClass const& data)
  63.     {
  64.         return os << "I'm in the class, msg=" << data.msg << endl;
  65.     }
  66.  
  67. private:
  68.     string msg;
  69. };