2、左移运算符重载.cpp 873 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. //4.5.2 左移运算符重载
  2. //作用 : 可以输出自定义数据类型
  3. #if(0)
  4. #include <iostream>
  5. class Person
  6. {
  7. public:
  8. Person(int a , int b)
  9. {
  10. m_A = a;
  11. m_B = b;
  12. }
  13. friend std::ostream& operator<<(std::ostream& cout, Person& p);
  14. //利用成员函数重载 左移运算符 p.operator<<(cout) 简化版本 p << cout
  15. //不会利用成员函数重载<<运算符,因为无法实现 cout 在左侧
  16. //void operator<< (cout)
  17. //{
  18. //}
  19. private:
  20. int m_A;
  21. int m_B;
  22. };
  23. //只能利用全局函数重载左移运算符
  24. std::ostream& operator<<(std::ostream &cout , Person &p) //本质 operator<< (cout,p) 简化 cout << p
  25. {
  26. std::cout << "m_A = " << p.m_A << " m_B = " << p.m_B;
  27. return cout;
  28. }
  29. void test01()
  30. {
  31. Person p(10,10);
  32. //p.m_A = 10;
  33. //p.m_B = 10;
  34. std::cout << p << std::endl;
  35. }
  36. int main()
  37. {
  38. test01();
  39. system("pause");
  40. return 0;
  41. }
  42. #endif