c++运算符重载电子时钟
时间: 2023-10-18 09:19:30 浏览: 96
以下是一个简单的电子时钟类,包含了重载运算符来实现时钟的加、减、比较等操作:
```c++
#include <iostream>
#include <iomanip>
using namespace std;
class Clock {
public:
Clock(int h = 0, int m = 0, int s = 0) : hour(h), minute(m), second(s) {}
void setTime(int h, int m, int s) { hour = h; minute = m; second = s; }
void showTime() const { cout << setfill('0') << setw(2) << hour << ':' << setw(2) << minute << ':' << setw(2) << second << endl; }
Clock operator+(int seconds) const;
Clock operator-(int seconds) const;
int operator-(const Clock& c) const;
bool operator<(const Clock& c) const;
bool operator>(const Clock& c) const;
bool operator==(const Clock& c) const;
private:
int hour, minute, second;
};
Clock Clock::operator+(int seconds) const {
Clock tmp(hour, minute, second + seconds);
if (tmp.second >= 60) {
tmp.second -= 60;
tmp.minute++;
}
if (tmp.minute >= 60) {
tmp.minute -= 60;
tmp.hour++;
}
tmp.hour %= 24;
return tmp;
}
Clock Clock::operator-(int seconds) const {
Clock tmp(hour, minute, second - seconds);
if (tmp.second < 0) {
tmp.second += 60;
tmp.minute--;
}
if (tmp.minute < 0) {
tmp.minute += 60;
tmp.hour--;
}
tmp.hour = (tmp.hour + 24) % 24;
return tmp;
}
int Clock::operator-(const Clock& c) const {
int t1 = hour * 3600 + minute * 60 + second;
int t2 = c.hour * 3600 + c.minute * 60 + c.second;
return (t1 - t2 + 86400) % 86400;
}
bool Clock::operator<(const Clock& c) const {
return (hour < c.hour || (hour == c.hour && (minute < c.minute || (minute == c.minute && second < c.second))));
}
bool Clock::operator>(const Clock& c) const {
return (hour > c.hour || (hour == c.hour && (minute > c.minute || (minute == c.minute && second > c.second))));
}
bool Clock::operator==(const Clock& c) const {
return (hour == c.hour && minute == c.minute && second == c.second);
}
int main() {
Clock c1(12, 0, 0), c2(0, 0, 0);
c1.showTime();
c2.showTime();
Clock c3 = c1 + 3600;
c3.showTime();
c3 = c3 - 1800;
c3.showTime();
cout << "c1 - c2 = " << c1 - c2 << endl;
cout << "c2 - c1 = " << c2 - c1 << endl;
cout << "c1 < c2: " << (c1 < c2) << endl;
cout << "c1 > c2: " << (c1 > c2) << endl;
cout << "c1 == c2: " << (c1 == c2) << endl;
cout << "c1 == c3: " << (c1 == c3) << endl;
return 0;
}
```
在该类中,我们重载了加、减、比较等运算符,使得可以直接对时钟对象进行加减、比较等操作。其中,加减运算的实现需要注意进位和借位的情况,而比较运算则需要按照小时、分钟、秒钟的顺序进行比较。
阅读全文