将单目运算符"++"重载为成员函数形式
对于前置单目运算符,重载函数没有形参,对于后置单目运算符,重载函数有一个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 std::cout << "Call front operator overloading" << std::endl; 42 _sec++; 43 if(_sec >= 60) 44 { 45 _sec = _sec - 60; 46 _min++; 47 if(_min >= 60) 48 { 49 _min = _min - 60; 50 _hour++; 51 _hour = _hour % 24; 52 } 53 } 54 return *this; 55 } 56 57 Clock Clock::operator++(int) 58 { 59 std::cout << "Call post operator overloading" << std::endl; 60 Clock old = *this; 61 ++(*this); //调用前置单目运算符重载函数 62 return old; 63 } 64 65 int main(int argc,char* argv[]) 66 { 67 Clock myClock(23,59,59); 68 cout << "current time: "; 69 myClock.showTime(); 70 ++myClock; 71 cout << "++myClock: "; 72 myClock.showTime(); 73 myClock++; 74 cout << "myClock++: "; 75 myClock.showTime(); 76 return 0; 77 }
输出结果:
current time: 23:59:59
Call front operator overloading
++myClock: 0:0:0
Call post operator overloading
Call front operator overloading
myClock++: 0:0:1
それでも私の大好きな人