作用:通过重载递增运算符,实现自己的整型数据

    总结:前置递增返回引用,后置递增返回值

    1. //左移运算符重载
    2. class MyInt
    3. {
    4. friend ostream& operator<<(ostream& out, MyInt myint);
    5. public:
    6. MyInt(int a = 0) :m_Num(a) {}
    7. //重载前置++运算符 返回引用是为了一直对一个数据进行操作
    8. //MyInt& operator++()
    9. //{
    10. // //先进行++运算
    11. // m_Num++;
    12. // //再将自身返回
    13. // return *this;
    14. //}
    15. //重载后置++运算符
    16. //operator++(int) int代表占位参数,可以用于区分前置和后置递增,并且只能写int,不能写别的数据类型
    17. MyInt operator++(int)
    18. {
    19. //先 记录当时结果
    20. MyInt tmp = *this;
    21. //后 递增
    22. m_Num++;
    23. //最后将记录结果做返回
    24. return tmp;
    25. }
    26. int m_Num;
    27. };
    28. //重载<<运算符
    29. ostream& operator<<(ostream& out, MyInt myint)
    30. {
    31. out << myint.m_Num;
    32. return out;
    33. }
    34. //++运算符重载全局函数
    35. MyInt& operator++(MyInt &myint)
    36. {
    37. //先进行++运算
    38. myint.m_Num++;
    39. //再将自身返回
    40. return myint;
    41. }
    42. void test01()
    43. {
    44. MyInt i(10);
    45. cout << ++(++i) << endl;
    46. }
    47. void test02()
    48. {
    49. MyInt myint;
    50. cout << myint++ << endl;
    51. cout << myint << endl;
    52. }
    53. int main()
    54. {
    55. test01();
    56. test02();
    57. system("pause");
    58. return 0;
    59. }