1 #include <iostream> 2 #include <string> 3 using namespace std; 4 5 //重载递增运算符 6 7 //自定义整形 8 class MyInteger 9 { 10 friend ostream& operator<<(ostream& cout, MyInteger myint); 11 public: 12 MyInteger() 13 { 14 m_Num = 0; 15 } 16 17 //重载 前置++运算符 返回引用为了对一个数据进行++ 18 //返回引用 19 MyInteger& operator++() 20 { 21 22 //先进行 ++运算 23 m_Num++; 24 25 //再将自身作为返回 26 return *this; 27 } 28 29 30 //重载后置++运算符 31 //void operator++(int) int 代表占位参数,可以用于区分前置喝后置递增 32 //返回值 33 MyInteger operator++(int) 34 { 35 //先记录当时结果 36 MyInteger temp = *this; 37 38 //后 递增 39 m_Num++; 40 //最后将结果返回 41 return temp; 42 } 43 44 45 private: 46 int m_Num; 47 }; 48 49 //重载 <<运算符 50 ostream& operator<<(ostream& cout, MyInteger myint) 51 { 52 cout << myint.m_Num; 53 return cout; 54 } 55 56 57 void test01() 58 { 59 MyInteger myint; 60 61 cout << ++(++myint) << endl; //2 62 cout << myint << endl; //2 63 } 64 65 void test02() 66 { 67 MyInteger myint; 68 69 cout << myint++ << endl; //0 70 71 cout << myint<< endl; //1 72 73 } 74 75 76 int main() 77 { 78 test01(); 79 test02(); 80 }