#include using namespace std;

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; }

C++ 时间类实现:重载运算符,比较时间,推后提前

原文地址: https://www.cveoy.top/t/topic/nShZ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录