编写一个程序,定义一个时间类Time,包含三个属性: hour, minute 和 second 要求通过运算符重载实现如下功能: 时间输入输出(>>、<<); 时间增加减少若干(+=、-=),例:Time& operator+=(const Time&);Time& operator-=(const Time&); 时间前、后自增加/减少1秒(++、--),前自增例:Time& operator++(); 后自增例:Time operator++(int); 【输入形式】 输入固定为两个Time实例(time1,time2),每个实例占一行; Time实例输入格式为:hour minute second。 【输出形式】 Time实例输出格式为:hour:minute:second; 每个输出实例占一行。 依次输出以下表达式的值 time1 += (time2++) time1 -= time2 ++time2 time2 += (time1--) --time1 time2 -= time1
时间: 2023-06-03 09:06:01 浏览: 610
+ 10;时间与整数相乘( * ),例:Time * 2;时间比较大小( <、> )。能否给出代码示例?
好的,以下是时间类Time的代码示例:
```c++
#include<iostream>
using namespace std;
class Time {
friend ostream& operator<<(ostream&, const Time&);
friend istream& operator>>(istream&, Time&);
public:
Time(int h = 0, int m = 0, int s = 0) {
hour = h;
minute = m;
second = s;
}
Time& operator+=(int s) {
second += s;
minute += second / 60;
second %= 60;
hour += minute / 60;
minute %= 60;
return *this;
}
Time& operator-=(int s) {
second -= s;
if (second < 0) {
second += 60;
minute--;
}
minute -= second / 60;
if (minute < 0) {
minute += 60;
hour--;
}
hour -= minute / 60;
if (hour < 0) {
hour += 24;
}
return *this;
}
Time operator+(int s) const {
Time t(*this);
return t += s;
}
Time operator-(int s) const {
Time t(*this);
return t -= s;
}
Time operator*(int s) const {
Time t(*this);
int total = ((hour * 60 + minute) * 60 + second) * s;
t.second = total % 60;
total /= 60;
t.minute = total % 60;
total /= 60;
t.hour = total % 24;
return t;
}
bool operator<(const Time& t) const {
if (hour != t.hour) {
return hour < t.hour;
}
else if (minute != t.minute) {
return minute < t.minute;
}
else {
return second < t.second;
}
}
bool operator>(const Time& t) const {
return t < *this;
}
private:
int hour, minute, second;
};
ostream& operator<<(ostream& os, const Time& t) {
os << t.hour << ":" << t.minute << ":" << t.second;
return os;
}
istream& operator>>(istream& is, Time& t) {
is >> t.hour >> t.minute >> t.second;
return is;
}
int main() {
Time t1(8, 10, 0), t2(22, 45, 30);
Time t3;
int s = 3600;
cout << "t1 is " << t1 << endl;
cout << "t2 is " << t2 << endl;
cout << "Enter a time (hour minute second):";
cin >> t3;
cout << "You entered " << t3 << endl;
t1 += s;
cout << "t1 after adding " << s << " seconds is " << t1 << endl;
t2 -= s;
cout << "t2 after subtracting " << s << " seconds is " << t2 << endl;
Time t4 = t3 * 3;
cout << "t3 * 3 is " << t4 << endl;
if (t1 < t2) {
cout << "t1 is earlier than t2" << endl;
}
else {
cout << "t1 is later than t2" << endl;
}
return 0;
}
```
阅读全文