定义时间类 Time时间的表示采用 24 小时制。重载运算符和实现时间的输出和输入;重载运算符+和-实现时间推后和提前若干分钟;重载运算符++和--实现当前时间推后和提前 1 小时;重载、、==!=来判断两个时间之间大于、小于、等于以及不等于的关系
#include
class Time { private: int hour; int minute; public: Time(int h = 0, int m = 0) { hour = h; minute = m; } friend ostream& operator<<(ostream& os, const Time& t) { os << t.hour << ":" << t.minute; return os; } friend istream& operator>>(istream& is, Time& t) { char ch; is >> t.hour >> ch >> t.minute; return is; } Time operator+(int minutes) { Time t(hour, minute + minutes); t.hour += t.minute / 60; t.minute %= 60; return t; } Time operator-(int minutes) { Time t(hour, minute - minutes); t.hour += t.minute / 60; t.minute %= 60; return t; } Time operator++() { hour++; if (hour == 24) hour = 0; return *this; } Time operator--() { hour--; if (hour == -1) hour = 23; return *this; } bool operator>(const Time& t) const { if (hour > t.hour) return true; else if (hour < t.hour) return false; else return minute > t.minute; } bool operator<(const Time& t) const { if (hour < t.hour) return true; else if (hour > t.hour) return false; else return minute < t.minute; } bool operator==(const Time& t) const { return hour == t.hour && minute == t.minute; } bool operator!=(const Time& t) const { return !(*this == t); } };
int main() { Time t1, t2; cout << "请输入时间1:"; cin >> t1; cout << "请输入时间2:"; cin >> t2; cout << "时间1为:" << t1 << endl; cout << "时间2为:" << t2 << endl; cout << "时间1 + 30分钟为:" << t1 + 30 << endl; cout << "时间2 - 15分钟为:" << t2 - 15 << endl; cout << "时间1推后1小时为:" << ++t1 << endl; cout << "时间2提前1小时为:" << --t2 << endl; if (t1 > t2) { cout << "时间1晚于时间2" << endl; } else if (t1 < t2) { cout << "时间1早于时间2" << endl; } else { cout << "时间1等于时间2" << endl; } if (t1 != t2) { cout << "时间1不等于时间2" << endl; } else { cout << "时间1等于时间2" << endl; } return 0;
原文地址: https://www.cveoy.top/t/topic/ewhK 著作权归作者所有。请勿转载和采集!