C++定义一个时间类,能提供和设置时分秒组成的时间,并写出应用程序、定义时间对象、设置时间、输出该对象提供的时间
时间: 2023-05-30 19:02:30 浏览: 409
#include <iostream>
using namespace std;
class Time {
private:
int hour;
int minute;
int second;
public:
void setTime(int h, int m, int s) {
hour = h;
minute = m;
second = s;
}
void getTime() {
cout << "Time is: " << hour << ":" << minute << ":" << second << endl;
}
};
int main() {
Time t1; //定义时间对象
t1.setTime(12, 30, 45); //设置时间
t1.getTime(); //输出该对象提供的时间
return 0;
}
相关问题
c++ 定义一个时间类,能提供和设置由时、分、秒组成的时间
以下是一个C++的时间类的定义,可以提供和设置由时、分、秒组成的时间:
```cpp
class Time {
private:
int hour;
int minute;
int second;
public:
Time(int h = 0, int m = 0, int s = 0) {
hour = h;
minute = m;
second = s;
}
// 获取和设置时间
int getHour() const { return hour; }
int getMinute() const { return minute; }
int getSecond() const { return second; }
void setHour(int h) { hour = h; }
void setMinute(int m) { minute = m; }
void setSecond(int s) { second = s; }
// 显示时间
void showTime() const {
printf("%02d:%02d:%02d\n", hour, minute, second);
}
};
```
使用示例:
```cpp
int main() {
Time t(8, 30, 0); // 初始化时间为8:30:00
t.showTime(); // 输出时间
t.setHour(9); // 修改小时为9
t.showTime(); // 输出时间
return 0;
}
```
定义一个时间类Time,能提供和设置由时,分,秒组成的时间,并编出应用程序,定义时间对象,设置时间,输出该对象提供的时间(用C++
好的,以下是时间类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`等函数,保证了输出格式的统一和美观。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)