对于前置单目运算符,重载函数没有形参,对于后置单目运算符,重载函数有一个int型形参。这个int型参数在函数体中并不使用,纯粹是用来区别前置与后置,因此参数表中可以只给出类型名,没有参数名。
1 #include <iostream> 2 3 using namespace std; 4 5 class Clock 6 { 7 public: 8 Clock(int hour = 0,int min = 0,int sec = 0); 9 void showTime(); 10 Clock& operator++(); //前置单目运算符重载 11 Clock operator++(int); //后置单目运算符重载 12 private: 13 int _hour; 14 int _min; 15 int _sec; 16 }; 17 18 Clock::Clock(int hour,int min,int sec) 19 { 20 if(0 <= hour && hour < 24 21 && 0 <= min && min < 60 22 && 0 <= sec && sec < 60) 23 { 24 _hour = hour; 25 _min = min; 26 _sec = sec; 27 } 28 else 29 { 30 cout << "Time Init error." << endl; 31 } 32 } 33 34 void Clock::showTime() 35 { 36 cout << _hour << ":" << _min << ":" << _sec << endl; 37 } 38 39 Clock& Clock::operator++() 40 { 41 _sec++; 42 if(_sec >= 60) 43 { 44 _sec = _sec - 60; 45 _min++; 46 if(_min >= 60) 47 { 48 _min = _min - 60; 49 _hour++; 50 _hour = _hour % 24; 51 } 52 } 53 return *this; 54 } 55 56 Clock Clock::operator++(int) 57 { 58 Clock old = *this; 59 ++(*this); //调用前置单目运算符重载函数 60 return old; 61 } 62 63 int main(int argc,char* argv[]) 64 { 65 Clock myClock(23,59,59); 66 cout << "First time output: " ; 67 myClock.showTime(); 68 cout << "Show myClock++: "; 69 myClock++; 70 myClock.showTime(); 71 cout << "Show ++myClock: "; 72 (++myClock).showTime(); 73 return 0; 74 }