3、递增运算符重载.cpp 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. //4.5.3 递增运算符重载
  2. //作用:通过重载递增运算符,实现自己的整形数据
  3. #if(0)
  4. #include <iostream>
  5. class MyInteger
  6. {
  7. friend std::ostream& operator<<(std::ostream& cout, MyInteger myint);
  8. public:
  9. MyInteger()
  10. {
  11. m_Num = 0;
  12. }
  13. //重载前置++运算符 返回引用为了一直对一个数据进行递增操作
  14. MyInteger& operator++()
  15. {
  16. //先进行++运算
  17. m_Num++;
  18. //再将自身做返回
  19. return *this;
  20. }
  21. //重载后置++运算符
  22. //void operator++(int) int代表的是一个占位参数 可以用于区分前置和后置递增
  23. MyInteger operator++(int)
  24. {
  25. //先 记录当时结果
  26. MyInteger temp = *this;
  27. //后 递增
  28. m_Num++;
  29. //最后将记录结果做返回
  30. return temp;
  31. }
  32. private:
  33. int m_Num;
  34. };
  35. //重载<<运算符
  36. std::ostream& operator<<(std::ostream&cout , MyInteger myint)
  37. {
  38. std::cout << myint.m_Num;
  39. return cout;
  40. }
  41. void test01()
  42. {
  43. MyInteger myint;
  44. std::cout << ++(++myint) << std::endl;
  45. std::cout << myint << std::endl;
  46. }
  47. void test02()
  48. {
  49. MyInteger myint;
  50. std::cout << myint++ << std::endl;
  51. std::cout << myint << std::endl;
  52. }
  53. int main()
  54. {
  55. //test01();
  56. test02();
  57. //int a = 0;
  58. //std::cout << ++(++a) << std::endl;
  59. //std::cout << a << std::endl;
  60. system("pause");
  61. return 0;
  62. }
  63. #endif
  64. //总结 :前置递增返回的是引用,后置递增返回的是值