1 #include <iostream> 2 using namespace std; 3 4 class Increase 5 { 6 public: 7 Increase() { value = 0; } 8 void display() const { cout << value << endl;}; 9 10 Increase operator ++ (); // 前置 ++ 的重载函数(成员函数) 11 Increase operator ++ (int); // 后置 ++ 的重载函数(成员函数) 12 13 private: 14 unsigned value; 15 }; 16 17 Increase Increase :: operator ++() 18 { 19 value++; 20 return *this; 21 } 22 23 Increase Increase :: operator ++(int) 24 { 25 Increase temp; 26 //temp.value = value++; // 相当于下面两句 27 temp.value = value; // 保存为改变的前的值 28 this->value = value + 1; 29 return temp; 30 } 31 32 int main() 33 { 34 Increase a, b, n, m; 35 for ( int i = 0; i < 10; i++) 36 a = n++; 37 cout << "n = "; 38 n.display(); // n = 10 39 cout << "a = "; 40 a.display(); // a = 9 41 42 for( int i = 0; i < 10; i++) 43 b = ++m; 44 cout << "m = "; // 10 45 n.display(); 46 cout << "b = "; // 10 47 b.display(); 48 49 return 0; 50 }
浙公网安备 33010602011771号