定义一个时间类Time,能提供和设置由时、分、秒组成的时间,并编写应用程序,定义时间对象,设置时间,输出该对象提供的时间。并请将类定义作为接口,用多文件结构实现之。
时间: 2023-10-05 12:07:22 浏览: 50
好的,下面是时间类Time的定义(包含接口和实现):
```c++
// Time.h
#ifndef TIME_H
#define TIME_H
class Time {
public:
Time();
Time(int h, int m, int s);
void setTime(int h, int m, int s);
void printTime();
private:
int hour;
int minute;
int second;
};
#endif
```
```c++
// Time.cpp
#include <iostream>
#include "Time.h"
using namespace std;
Time::Time() {
hour = 0;
minute = 0;
second = 0;
}
Time::Time(int h, int m, int s) {
setTime(h, m, s);
}
void Time::setTime(int h, int m, int s) {
hour = h;
minute = m;
second = s;
}
void Time::printTime() {
cout << hour << ":" << minute << ":" << second << endl;
}
```
接下来是应用程序代码:
```c++
// main.cpp
#include "Time.h"
int main() {
Time t(10, 30, 0);
t.printTime();
t.setTime(12, 45, 20);
t.printTime();
return 0;
}
```
编译和运行程序:
```
$ g++ -c Time.cpp
$ g++ -c main.cpp
$ g++ Time.o main.o -o TimeApp
$ ./TimeApp
10:30:0
12:45:20
```
上述代码中,Time.h 文件包含了 Time 类的接口,Time.cpp 包含了 Time 类的实现,main.cpp 文件则用到了 Time 类。在编译时需要将 Time.cpp 和 main.cpp 一起编译成一个可执行文件。
相关推荐
![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)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)