【问题描述】对时钟类进行重载【输入形式】
【输出形式】
【样例输入】
【样例输出】
【样例说明】
【评分标准】
代码如下:
#include <iostream>
using namespace std;
class Clock //时钟类声明
{
public: //外部接口
Clock(int NewH=0, int NewM=0, int NewS=0);
void ShowTime();
Clock operator ++(); //前置单目运算符重载
//后置单目运算符重载
Clock operator++(int);
//+运算符重载
Clock operator+(const Clock& other) {
int newHour = (Hour + other.Hour) % 24;
int newMinute = Minute + other.Minute;
int newSecond = Second + other.Second;
if (newSecond >= 60) {
newSecond -= 60;
newMinute++;
}
if (newMinute >= 60) {
newMinute -= 60;
newHour = (newHour + 1) % 24;
}
return Clock(newHour, newMinute, newSecond);
}
private: //私有数据成员
int Hour, Minute, Second;
};
Clock Clock::operator++() {
Second++;
if (Second >= 60) {
Second -= 60;
Minute++;
if (Minute >= 60) {
Minute -= 60;
Hour = (Hour + 1) % 24;
}
}
return *this;
}
Clock Clock::operator++(int) {
Clock temp(*this);
++(*this);
return temp;
}
Clock::Clock(int NewH, int NewM, int NewS) {
Hour = NewH;
Minute = NewM;
Second = NewS;
}
void Clock::ShowTime()
{
cout<<Hour<<":"<<Minute<<":"<<Second<<endl;
}
int main()
{
Clock c1(23,59,59),c2(5,12,10),c3;
c1.ShowTime();
c1++;
c1.ShowTime();
c3=++c2;
c3.ShowTime();
c3=c2+c1;
c3.ShowTime();
return 0;
}