1 #include<iostream> 2 #include<iomanip> 3 using namespace std; 4 class Clock{ 5 int hour; 6 int minute; 7 int second; 8 public: 9 Clock(int hour=0, int minute=0, int second=0); 10 11 void setTime(int hour, int minute, int second); 12 void showTime(); 13 14 bool operator > (Clock& c); 15 bool operator < (Clock& c); 16 }; 17 //构造 18 Clock::Clock(int hour, int minute, int second) 19 { 20 this->hour = hour; 21 this->minute = minute; 22 this->second = second; 23 } 24 //设置 25 void Clock::setTime(int hour, int minute, int second) 26 { 27 this->hour = hour; 28 this->minute = minute; 29 this->second = second; 30 } 31 //显示 32 void Clock::showTime(){ 33 cout<<setw(2)<<setfill('0')<<hour<<":"; 34 cout<<setw(2)<<setfill('0')<<minute<<":"; 35 cout<<setw(2)<<setfill('0')<<second<<":"; 36 cout<<endl; 37 } 38 //重载> 39 bool Clock::operator > (Clock& c){ 40 return (hour*60*60 + minute*60 + second)> 41 (c.hour*60*60 + c.minute*60 + c.second); 42 } 43 //重载< 44 bool Clock::operator < (Clock& c){ 45 return (hour*60*60 + minute*60 + second)< 46 (c.hour*60*60 + c.minute*60 + c.second); 47 } 48 /* //友元函数,运算符重载 49 friend bool operator > (Clock& c1,Clock& c2){ 50 return (hour*60*60 + minute*60 + second)> 51 (c.hour*60*60 + c.minute*60 + c.second); 52 } 53 friend bool operator < (Clock& c1,Clock& c2){ 54 return (hour*60*60 + minute*60 + second)< 55 (c.hour*60*60 + c.minute*60 + c.second); 56 } 57 */ 58 int main() 59 { 60 Clock c1,c2; 61 c1.showTime(); 62 c2.showTime(); 63 64 c1.setTime(1,55,30); 65 c2.setTime(12,4,55); 66 c1.showTime(); 67 c2.showTime(); 68 69 bool timeCompare = c1>c2; 70 cout<<"c1>c2=" << boolalpha << timeCompare << endl; 71 72 timeCompare = c1<c2; 73 cout<<"c1<c2=" << boolalpha << timeCompare << endl; 74 return 0; 75 }