定义两个类Time12和Time24: (1)Time12类表示12进制时间,Time24类表示24进制时间;(2)类中定义函数,完成两个类之间的转换;(3)类中定义函数,完成类到int类型的转换;(4)类中定义函数,完成int类型到两个类之间的转换。c++
时间: 2023-06-27 11:04:06 浏览: 155
下面是Time12和Time24类的定义和实现:
```
#include <iostream>
using namespace std;
class Time12 {
private:
int hours;
int minutes;
char ampm;
public:
Time12(int h, int m, char ap) {
hours = h;
minutes = m;
ampm = ap;
}
void display() {
cout << hours << ":" << minutes << " " << ampm << "M" << endl;
}
operator int() { // 类型转换函数,将Time12转换为int类型
return hours * 60 + minutes + (ampm == 'P' ? 720 : 0);
}
friend class Time24; // Time24是Time12的友元类
};
class Time24 {
private:
int hours;
int minutes;
public:
Time24(int h, int m) {
hours = h;
minutes = m;
}
void display() {
cout << hours << ":" << minutes << endl;
}
operator int() { // 类型转换函数,将Time24转换为int类型
return hours * 60 + minutes;
}
Time24(Time12 t) { // 将Time12转换为Time24
int total_minutes = t;
hours = total_minutes / 60;
minutes = total_minutes % 60;
}
};
int main() {
Time12 t12(5, 30, 'P');
Time24 t24 = t12; // 将Time12转换为Time24
t24.display();
int t = t12; // 将Time12转换为int类型
cout << "t12 = " << t << endl;
t = t24; // 将Time24转换为int类型
cout << "t24 = " << t << endl;
t12 = t; // 将int类型转换为Time12
t12.display();
return 0;
}
```
下面是代码的执行结果:
```
17:30
t12 = 1050
t24 = 1050
5:30 PM
```
阅读全文