实验(1):定义时间(CMyTime),有小时、分钟和秒三个成员变量,重载“-”(减)、后置“++”和“>=”运算符,实现函数show 显示时间,测试MyTime。c++
时间: 2024-03-14 13:43:17 浏览: 25
下面是 C++ 的代码实现:
```cpp
#include <iostream>
using namespace std;
class CMyTime {
private:
int hour, minute, second;
public:
CMyTime(int h=0, int m=0, int s=0):hour(h), minute(m), second(s) {}
friend CMyTime operator-(const CMyTime& t1, const CMyTime& t2);
CMyTime operator++(int);
bool operator>=(const CMyTime& t) const;
void show() const;
};
CMyTime operator-(const CMyTime& t1, const CMyTime& t2) {
int s1 = t1.hour * 3600 + t1.minute * 60 + t1.second;
int s2 = t2.hour * 3600 + t2.minute * 60 + t2.second;
int diff = s1 - s2;
if (diff < 0)
diff += 3600 * 24;
return CMyTime(diff / 3600, (diff % 3600) / 60, diff % 60);
}
CMyTime CMyTime::operator++(int) {
CMyTime tmp(*this);
second++;
if (second >= 60) {
second -= 60;
minute++;
if (minute >= 60) {
minute -= 60;
hour++;
if (hour >= 24) {
hour = 0;
}
}
}
return tmp;
}
bool CMyTime::operator>=(const CMyTime& t) const {
int s1 = hour * 3600 + minute * 60 + second;
int s2 = t.hour * 3600 + t.minute * 60 + t.second;
return s1 >= s2;
}
void CMyTime::show() const {
cout << hour << ":" << minute << ":" << second << endl;
}
int main() {
CMyTime t1(12, 30, 45), t2(8, 20, 30), t3;
t3 = t1 - t2;
t3.show();
t1++;
t1.show();
if (t1 >= t2) {
cout << "t1 >= t2" << endl;
}
else {
cout << "t1 < t2" << endl;
}
return 0;
}
```
该程序定义了一个 CMyTime 类,其中包含了小时、分钟和秒三个成员变量,还重载了减、后置自增和大于等于三个运算符。其中,减法运算符重载为全局函数,后置自增和大于等于运算符都重载为成员函数。show 函数用于显示时间。
在 main 函数中,创建了三个 CMyTime 类型的对象,分别表示12:30:45、8:20:30和默认时间。测试了减法、后置自增和大于等于运算符的重载效果,并输出了测试结果。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)