题目:

设计一个时钟类TIME,内含数据成员hour,minute,second表示时间,成员函数set( )设置时间数据,show( )显示时间数据。

重载运算符 ++和– (具有返回值),每执行一次++,second自增1,执行一次–,second自减1。

second和minute的值在0 ~ 59区间循环(满59后再自增则归0,minute加1;second为0时再自减则为59,minute减1)。hour的值在0 ~ 23区间循环。

参考:

#include <iostream>
using namespace std;
class TIME {
private:
int hour;
int minute;
int second;
TIME ruler(void); //用于规范时间的格式,
public:
TIME();
TIME(int, int, int);
void sethour(int);
void setminute(int);
void setsecond(int);
TIME operator++();
TIME operator++(int);
TIME operator--();
TIME operator--(int);
void print(void);
};
TIME::TIME() :hour(0), minute(0), second(0) { }
TIME::TIME(int h = 0, int m = 0, int s = 0) : hour(h), minute(m), second(s) {
this->ruler();
}
TIME TIME::ruler() {
if (second > 59) {
second %= 60;
minute++;
}
if (minute > 59) {
minute %= 60;
hour++;
}
if (hour > 23) {
hour %= 24;
}
if (second < 0) {
second = second % 60 + 60;
minute--;
}
if (minute < 0) {
minute = minute % 60 + 60;
hour--;
}
if (hour < 0) {
hour = hour % 24 + 24;
}
return *this;
}
void TIME::sethour(int h) {
hour = h;
}
void TIME::setminute(int m) {
minute = m;
}
void TIME::setsecond(int s) {
second = s;
}
void TIME::print() {
cout << hour << ":" << minute << ":" << second << endl;
}
TIME TIME::operator++() {
++second;
this->ruler();
return *this;
}
TIME TIME::operator++(int) {
TIME p(*this);
second++;
this->ruler();
return p;
}
TIME TIME::operator--() {
--second;
this->ruler();
return *this;
}
TIME TIME::operator--(int) {
TIME p(*this);
second--;
this->ruler();
return p;
}
int main() {
TIME t(23, 59, 59);
t.print();
++t;
t.print();
--t;
t.print();

TIME p1 = t++;
p1.print();
TIME p2 = t--;
p2.print();
return 0;
}

图片版:

code