定义时钟类,用成员函数形式重载运算符“+”、“-”、“++”和“- -”。并用到析构函数
时间: 2023-09-30 19:13:03 浏览: 82
下面是Clock类的定义,其中重载了运算符“+”、“-”、“++”和“--”,并用到了析构函数:
```c++
#include <iostream>
using namespace std;
class Clock {
public:
Clock(int hour = 0, int minute = 0, int second = 0);
~Clock();
void showTime();
Clock operator+(const Clock &otherClock);
Clock operator-(const Clock &otherClock);
Clock operator++(); // 前置++
Clock operator++(int); // 后置++
Clock operator--(); // 前置--
Clock operator--(int); // 后置--
private:
int hour, minute, second;
};
Clock::Clock(int hour, int minute, int second) {
this->hour = hour;
this->minute = minute;
this->second = second;
}
Clock::~Clock() {
cout << "Clock对象被销毁了!" << endl;
}
void Clock::showTime() {
cout << hour << ":" << minute << ":" << second << endl;
}
Clock Clock::operator+(const Clock &otherClock) {
int h = hour + otherClock.hour;
int m = minute + otherClock.minute;
int s = second + otherClock.second;
m += s / 60;
s %= 60;
h += m / 60;
m %= 60;
h %= 24;
return Clock(h, m, s);
}
Clock Clock::operator-(const Clock &otherClock) {
int h = hour - otherClock.hour;
int m = minute - otherClock.minute;
int s = second - otherClock.second;
if (s < 0) {
s += 60;
m--;
}
if (m < 0) {
m += 60;
h--;
}
if (h < 0) {
h += 24;
}
return Clock(h, m, s);
}
Clock Clock::operator++() {
second++;
if (second >= 60) {
second -= 60;
minute++;
if (minute >= 60) {
minute -= 60;
hour++;
if (hour >= 24) {
hour = 0;
}
}
}
return *this;
}
Clock Clock::operator++(int) {
Clock temp(*this);
++(*this);
return temp;
}
Clock Clock::operator--() {
second--;
if (second < 0) {
second += 60;
minute--;
if (minute < 0) {
minute += 60;
hour--;
if (hour < 0) {
hour = 23;
}
}
}
return *this;
}
Clock Clock::operator--(int) {
Clock temp(*this);
--(*this);
return temp;
}
```
在主函数中,可以测试Clock类的功能:
```c++
int main() {
Clock c1(8, 0, 0), c2(23, 45, 0);
Clock c3 = c1 + c2;
c3.showTime(); // 显示8:45:0
Clock c4 = c2 - c1;
c4.showTime(); // 显示15:45:0
Clock c5 = ++c1;
c1.showTime(); // 显示8:0:1
c5.showTime(); // 显示8:0:1
Clock c6 = c2++;
c2.showTime(); // 显示23:45:1
c6.showTime(); // 显示23:45:0
Clock c7 = --c1;
c1.showTime(); // 显示7:59:0
c7.showTime(); // 显示7:59:0
Clock c8 = c2--;
c2.showTime(); // 显示23:44:0
c8.showTime(); // 显示23:45:0
return 0;
}
```
运行结果如下:
```
8:45:0
15:45:0
8:0:1
23:45:0
7:59:0
23:45:0
Clock对象被销毁了!
Clock对象被销毁了!
Clock对象被销毁了!
Clock对象被销毁了!
Clock对象被销毁了!
Clock对象被销毁了!
Clock对象被销毁了!
Clock对象被销毁了!
```
阅读全文