用C++编写一个程序,编写一个时钟类,数据成员为时、分、秒,成员函数包括设置时间函数、返回时间函数、构造函数、析构函数。在主函数中定义该类对象,调用相应函数进行测试
时间: 2024-02-05 09:03:32 浏览: 30
好的,以下是用C++编写的时钟类程序:
```c++
#include <iostream>
using namespace std;
class Clock {
public:
Clock(int h = 0, int m = 0, int s = 0); // 构造函数
~Clock(); // 析构函数
void setTime(int h, int m, int s); // 设置时间
void getTime(int& h, int& m, int& s); // 返回时间
private:
int hour, minute, second;
};
Clock::Clock(int h, int m, int s) {
hour = h;
minute = m;
second = s;
}
Clock::~Clock() {
cout << "时钟已经销毁!" << endl;
}
void Clock::setTime(int h, int m, int s) {
hour = h;
minute = m;
second = s;
}
void Clock::getTime(int& h, int& m, int& s) {
h = hour;
m = minute;
s = second;
}
int main() {
Clock c(12, 30, 0);
int h, m, s;
c.getTime(h, m, s);
cout << "当前时间为:" << h << ":" << m << ":" << s << endl;
c.setTime(18, 30, 0);
c.getTime(h, m, s);
cout << "设置后的时间为:" << h << ":" << m << ":" << s << endl;
return 0;
}
```
在主函数中,我们首先创建了一个时钟对象 c,时间为 12:30:00。然后调用 getTime 函数获取当前时间,并输出到控制台。
接着,我们调用 setTime 函数将时间设置为 18:30:00,并再次调用 getTime 函数获取时间,输出到控制台。
程序运行结果如下:
```
当前时间为:12:30:0
设置后的时间为:18:30:0
时钟已经销毁!
```
相关推荐
![](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)