注意前置运算符先++后返回,后置运算符先返回后- -
#include <iostream>
#include <iomanip>
using namespace std;
class Time {
int h, m, s;
public:
//Constructor & Destructor :
Time() :h(0), m(0), s(0) {}
Time(int hh, int mm, int ss) :h(hh), m(mm), s(ss) {}
Time(Time& t) {
h = t.h; m = t.m; s = t.s;
}
~Time() {}
void showTime() {
if (h >= 0 && h < 24 && m >= 0 && m <= 59 && s >= 0 && s <= 59)
cout << setw(2) << setfill('0') << h << ":" << setw(2) << setfill('0') << m << ":" << setw(2) << setfill('0') << s << endl;
else cout << "Time error" << endl;
}
friend ostream& operator<<(ostream& os,const Time &t) {
if (t.h >= 0 && t.h < 24 && t.m >= 0 && t.m <= 59 && t.s >= 0 && t.s <= 59)
os << setw(2) << setfill('0') << t.h << ":" << setw(2) << setfill('0') << t.m << ":" << setw(2) << setfill('0') << t.s;
else os << "error!!!";
return os;
}
friend istream& operator>>(istream& is, Time &t) {
/*int a, b, c;
is >> a >> b >> c;
if (a >= 0 && a < 24 && b >= 0 && b <= 59 && c >= 0 && c <= 59)
{
t.h = a; t.m = b; t.s = c;
}
else cout << "error!!!";*/
//h = t.h; m = t.m; s = t.s;
is >> t.h >> t.m >> t.s;
return is;
}
//每次++或--都要判断是否合法
//重写++t,前置先++后返回
Time& operator++() {
if (h >= 0 && h < 24 && m >= 0 && m <= 59 && s >= 0 && s <= 59) {
//合法,++后返回
s++;
if (s > 59) {
m++;
s = 0;
if (m > 59) {
h++; m = 0;
if (h > 23) {
h = 0;
}
}
}
}
//非法,直接返回
return *this;
}
//重写t++,后置先返回后++(即最后的返回值为未++之前的值)
Time operator++(int){
Time tmp = (*this);//记录未++之前的值,并返回此值
if (h >= 0 && h < 24 && m >= 0 && m <= 59 && s >= 0 && s <= 59) {
//合法,++后返回
s++;
if (s > 59) {
m++;
s = 0;
if (m > 59) {
h++; m = 0;
if (h > 23) {
h = 0;
}
}
}
}
//非法,直接返回
return tmp;
}
//重写--t,前置
Time& operator--() {
if (h >= 0 && h < 24 && m >= 0 && m <= 59 && s >= 0 && s <= 59) {
s--;
if (s < 0) {
s = 59;
m--;
if (m < 0) {
m = 59;
h--;
if (h < 0) {
h = 23;
}
}
}
}
return *this;
}
//重写t--,后置
Time operator--(int) {
Time tmp = (*this);//记录未--之前的值,并返回此值
if (h >= 0 && h < 24 && m >= 0 && m <= 59 && s >= 0 && s <= 59) {
s--;
if (s < 0) {
s = 59;
m--;
if (m < 0) {
m = 59;
h--;
if (h < 0) {
h = 23;
}
}
}
}
return tmp;
}
Time& inputTime()
{
int hour, min, sec;
cin >> hour;
cin >> min;
cin >> sec;
h = hour;
m = min;
s = sec;
return *this;
}
};
int main()
{
Time t;
int cases;
cin >> cases;
cout << setw(8) << left << "++t" << " ";
cout << setw(8) << left << "--t" << " ";
cout << setw(8) << left << "t" << " ";
cout << setw(8) << left << "t--" << " ";
cout << setw(8) << left << "t++" << " ";
cout << setw(8) << left << "t" << right << endl;
for (int i = 1; i <= cases; ++i)
{
cin >> t;
cout << (++t) << " ";
cout << (--t) << " ";
cout << t << " ";
cout << t-- << " ";
cout << t++ << " ";
cout << t << endl;
}
}