#include <iostream> #include <iomanip> using namespace std; class Time{ int hour, minute, second; public: Time(int h=0, int m=0, int s=0);//已实现 Time& operator++(); Time& operator--(); Time operator++(int); Time operator--(int); friend istream& operator>>(istream& in, Time& t);//已实现 friend ostream& operator<<(ostream& out, const Time& t);//已实现 };int main() { Time t; cin >> t; t++; cout << t << endl; --t; cout << t << endl; ++t; cout << t << endl; t--; cout << t << endl; return 0; } /* 请在这里填写答案,类设计及部分接口已有系统给出并实现,你只需要实现++和--运算符的重载 */
时间: 2023-06-19 17:04:13 浏览: 114
#include_iostream.h_
4星 · 用户满意度95%
可以参考以下代码实现++和--运算符的重载:
```c++
#include <iostream>
#include <iomanip>
using namespace std;
class Time{
int hour, minute, second;
public:
Time(int h=0, int m=0, int s=0);
Time& operator++(); // ++t
Time& operator--(); // --t
Time operator++(int); // t++
Time operator--(int); // t--
friend istream& operator>>(istream& in, Time& t);
friend ostream& operator<<(ostream& out, const Time& t);
};
Time::Time(int h, int m, int s) {
hour = h;
minute = m;
second = s;
}
Time& Time::operator++() {
second++;
if (second >= 60) {
second = 0;
minute++;
if (minute >= 60) {
minute = 0;
hour++;
if (hour >= 24) {
hour = 0;
}
}
}
return *this;
}
Time& Time::operator--() {
second--;
if (second < 0) {
second = 59;
minute--;
if (minute < 0) {
minute = 59;
hour--;
if (hour < 0) {
hour = 23;
}
}
}
return *this;
}
Time Time::operator++(int) {
Time temp(*this);
operator++();
return temp;
}
Time Time::operator--(int) {
Time temp(*this);
operator--();
return temp;
}
istream& operator>>(istream& in, Time& t) {
in >> t.hour >> t.minute >> t.second;
return in;
}
ostream& operator<<(ostream& out, const Time& t) {
out << setfill('0') << setw(2) << t.hour << ":" << setw(2) << t.minute << ":" << setw(2) << t.second;
return out;
}
int main() {
Time t;
cin >> t;
t++;
cout << t << endl;
--t;
cout << t << endl;
++t;
cout << t << endl;
t--;
cout << t << endl;
return 0;
}
```
阅读全文