<<)
时间相等判断(==)
时间比较大小(>)
时间加法(+)
时间减法(-)
可以这样实现:#include <iostream>using namespace std;class Time {public: int hour; int minute; int second; // 重载输入运算符 friend istream& operator>>(istream& input, Time& t) { input >> t.hour >> t.minute >> t.second; return input; } // 重载输出运算符 friend ostream& operator<<(ostream& output, const Time& t) { output << t.hour << ":" << t.minute << ":" << t.second; return output; } // 重载相等运算符 bool operator==(const Time& t) const { return (hour == t.hour && minute == t.minute && second == t.second); } // 重载大于运算符 bool operator>(const Time& t) const { if (hour > t.hour) { return true; } else if (hour == t.hour) { if (minute > t.minute) { return true; } else if (minute == t.minute) { if (second > t.second) { return true; } } } return false; } // 重载加法运算符 Time operator+(const Time& t) const { Time result; result.hour = hour + t.hour; result.minute = minute + t.minute; result.second = second + t.second; if (result.second >= 60) { result.minute += result.second / 60; result.second %= 60; } if (result.minute >= 60) { result.hour += result.minute / 60; result.minute %= 60; } if (result.hour >= 24) { result.hour %= 24; } return result; } // 重载减法运算符 Time operator-(const Time& t) const { int thisSeconds = hour * 3600 + minute * 60 + second; int tSeconds = t.hour * 3600 + t.minute * 60 + t.second; int diffSeconds = thisSeconds - tSeconds; Time result; result.hour = diffSeconds / 3600; result.minute = (diffSeconds % 3600) / 60; result.second = diffSeconds % 60; return result; }};int main() { Time t1, t2; cout << "请输入第一个时间(hh:mm:ss): "; cin >> t1; cout << "请输入第二个时间(hh:mm:ss): "; cin >> t2; cout << "第一个时间为: " << t1 << endl; cout << "第二个时间为: " << t2 << endl; if (t1 == t2) { cout << "两个时间相等" << endl; } else { cout << "两个时间不相等" << endl; } if (t1 > t2) { cout << "第一个时间大于第二个时间" << endl; } else { cout << "第一个时间小于等于第二个时间" << endl; } Time sum = t1 + t2; cout << "两个时间之和为: " << sum << endl; Time diff = t1 - t2; cout << "两个时间的差为: " << diff << endl; return 0;}
希望对你有所帮助!如果还有其他问题,请随时提问。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |