一、问题描述:
定义时钟类,单目运算符前置++和后置++重载的成员函数:以时钟类的对象为操作数。对于前置单目运算符,重载函数没有参数,对于后置单目运算符,重载函数有一个int型参数。
二、解题思路:
首先定义一个时钟类作为基类,再定义重载运算符的成员函数,最后在主函数中实现时钟类的对象的前置++和后置++的操作去验证代码的运行。
三、代码实现:
1 #include<iostream> 2 #include<string> 3 using namespace std; 4 class Clock 5 { 6 public: 7 Clock(int hour=0,int minute=0,int second=0); 8 void showTime() const; 9 Clock& operator++(); 10 Clock operator++(int); 11 private: 12 int hour,minute,second; 13 }; 14 Clock::Clock(int hour,int minute,int second) 15 { 16 if(0<=hour&&hour<24&&0<=minute&&minute<60&&0<=second&&second<60) 17 { 18 this->hour=hour; 19 this->minute=minute; 20 this->second=second; 21 } 22 else 23 cout<<"Time error!"<<endl; 24 } 25 void Clock::showTime() const 26 { 27 cout<<hour<<":"<<minute<<":"<<second<<endl; 28 } 29 Clock& Clock::operator++() 30 { 31 second++; 32 if(second>=60) 33 { 34 second-=60; 35 minute++; 36 if(minute>=60) 37 { 38 minute-=60; 39 hour=(hour+1)%24; 40 } 41 } 42 return *this; 43 } 44 Clock Clock::operator++(int) 45 { 46 Clock old=*this; 47 ++(*this); 48 return old; 49 } 50 int main() 51 { 52 Clock myClock(23,59,59); 53 cout<<"First time outputL:"; 54 myClock.showTime(); 55 cout<<"Show myClock++:"; 56 (myClock++).showTime(); 57 cout<<"Show++myClock:"; 58 (++myClock).showTime(); 59 return 0; 60 }
标签:21,hour,Clock,int,++,second,2023.4,打卡,minute From: https://www.cnblogs.com/lixinyao20223933/p/17342043.html