定义时钟类,用成员函数形式重载运算符“+”、“-”、“++”和“- -”。
时间: 2023-09-30 20:06:07 浏览: 46
下面是一个简单的时钟类的定义,其中重载了运算符“+”、“-”、“++”和“- -”。
```cpp
class Clock {
private:
int hour;
int minute;
int second;
public:
Clock(int h = 0, int m = 0, int s = 0) {
hour = h;
minute = m;
second = s;
}
void display() {
cout << hour << ":" << minute << ":" << second << endl;
}
Clock operator+(const Clock& c) {
Clock res;
res.second = second + c.second;
res.minute = minute + c.minute + res.second / 60;
res.second %= 60;
res.hour = hour + c.hour + res.minute / 60;
res.minute %= 60;
res.hour %= 24;
return res;
}
Clock operator-(const Clock& c) {
int s1 = hour * 3600 + minute * 60 + second;
int s2 = c.hour * 3600 + c.minute * 60 + c.second;
int diff = s1 - s2;
if (diff < 0) diff += 24 * 3600;
Clock res;
res.hour = diff / 3600;
res.minute = diff % 3600 / 60;
res.second = diff % 60;
return res;
}
Clock operator++() {
++second;
if (second >= 60) {
second %= 60;
++minute;
if (minute >= 60) {
minute %= 60;
++hour;
if (hour >= 24) {
hour %= 24;
}
}
}
return *this;
}
Clock operator++(int) {
Clock old = *this;
++(*this);
return old;
}
Clock operator--() {
--second;
if (second < 0) {
second += 60;
--minute;
if (minute < 0) {
minute += 60;
--hour;
if (hour < 0) {
hour += 24;
}
}
}
return *this;
}
Clock operator--(int) {
Clock old = *this;
--(*this);
return old;
}
};
```
这里我们定义了一个时钟类`Clock`,包含了时、分、秒三个成员变量。其中构造函数可以接受时分秒三个参数,并对它们进行初始化。`display()`函数用于显示当前时钟的时间。
接下来重载了四个运算符:
- “+”运算符:将两个时钟对象相加,得到一个新的时钟对象,表示两个时钟的时间之和。
- “-”运算符:将两个时钟对象相减,得到一个新的时钟对象,表示两个时钟的时间差。
- “++”运算符:将时钟对象的时间加1秒,并返回加1秒后的时钟对象。
- “- -”运算符:将时钟对象的时间减1秒,并返回减1秒后的时钟对象。
以上运算符的重载都是通过成员函数的形式实现的。