定义一个时间类Time,能提供和设置由时,分,秒组成的时间,并编出应用程序,定义时间对象,设置时间,输出该对象提供的时间(用C++
时间: 2023-10-04 07:04:03 浏览: 77
好的,以下是时间类Time的定义及应用程序(C++版):
```c++
#include <iostream>
#include <iomanip>
using namespace std;
class Time {
private:
int hour, minute, second;
public:
Time(int h=0, int m=0, int s=0) : hour(h), minute(m), second(s) {}
void set_time(int h, int m, int s) {
hour = h;
minute = m;
second = s;
}
string get_time() {
ostringstream oss;
oss << setfill('0') << setw(2) << hour << ":"
<< setfill('0') << setw(2) << minute << ":"
<< setfill('0') << setw(2) << second;
return oss.str();
}
};
int main() {
Time t;
t.set_time(10, 30, 45);
cout << t.get_time() << endl; // 输出结果为 10:30:45
return 0;
}
```
以上代码定义了一个时间类Time,提供了设置时间和获取时间的方法,应用程序中定义了一个时间对象t,设置其时间为10:30:45,并输出该对象提供的时间。
其中,私有属性`hour`,`minute`,`second`用来表示小时、分钟和秒数,防止外部直接修改属性值。`set_time`方法用来设置时间,`get_time`方法用来获取时间并返回可读的字符串形式。在输出时间时,使用了`ostringstream`和`setw`、`setfill`等函数,保证了输出格式的统一和美观。