C++定义一个时间类time++c++
时间: 2023-11-24 19:05:44 浏览: 108
#include <iostream>
using namespace std;
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;
}
void setTime(int h, int m, int s) {
hour = h;
minute = m;
second = s;
}
void showTime() {
cout << hour << ":" << minute << ":" << second << endl;
}
};
int main() {
Time t(12, 30, 45);
t.showTime();
return 0;
}
相关问题
c++定义一个时间类time
以下是一个简单的时间类 Time 的定义示例:
```cpp
#include <iostream>
using namespace std;
class Time
{
private:
int hours;
int minutes;
int seconds;
public:
// 构造函数
Time()
{
hours = 0;
minutes = 0;
seconds = 0;
}
Time(int h, int m, int s)
{
hours = h;
minutes = m;
seconds = s;
}
// 成员函数
void display()
{
cout << hours << ":" << minutes << ":" << seconds << endl;
}
// 运算符重载
Time operator+(const Time& t) const
{
int h = hours + t.hours;
int m = minutes + t.minutes;
int s = seconds + t.seconds;
if (s >= 60)
{
s -= 60;
m++;
}
if (m >= 60)
{
m -= 60;
h++;
}
Time sum(h, m, s);
return sum;
}
};
int main()
{
Time t1(9, 30, 0);
Time t2(1, 45, 30);
Time t3 = t1 + t2;
t1.display();
t2.display();
t3.display();
return 0;
}
```
这个时间类 Time 定义了三个私有变量:hours、minutes 和 seconds,表示小时、分钟和秒。它还定义了两个构造函数:一个默认构造函数和一个带参数的构造函数,用于初始化时间。它还定义了一个 display() 函数,用于显示时间值。
此外,它还重载了加号运算符,以便可以对两个时间对象进行加法运算。
在主函数中,它创建了三个时间对象,分别是 t1、t2 和 t3。然后将 t1 和 t2 相加,将结果存储在 t3 中,并显示所有三个时间对象的值。
c++定义一个time类,重载运算符
下面是一个简单的示例代码:
```c++
#include <iostream>
class Time {
public:
Time(int h, int m, int s) : hour(h), minute(m), second(s) {}
int getHour() const { return hour; }
int getMinute() const { return minute; }
int getSecond() const { return second; }
Time operator+(const Time& other) const {
int h = hour + other.hour;
int m = minute + other.minute;
int s = second + other.second;
if (s >= 60) {
m += s / 60;
s %= 60;
}
if (m >= 60) {
h += m / 60;
m %= 60;
}
return Time(h, m, s);
}
friend std::ostream& operator<<(std::ostream& os, const Time& t) {
os << t.hour << ":" << t.minute << ":" << t.second;
return os;
}
private:
int hour;
int minute;
int second;
};
int main() {
Time t1(10, 20, 30);
Time t2(1, 40, 50);
Time t3 = t1 + t2;
std::cout << t1 << " + " << t2 << " = " << t3 << std::endl;
return 0;
}
```
在上面的代码中,我们定义了一个 `Time` 类,它包含了小时、分钟和秒三个成员变量。我们重载了 `+` 运算符,让它能够实现两个 `Time` 对象的相加操作。同时,我们还重载了 `<<` 运算符,让它能够输出一个 `Time` 对象的值。在 `main` 函数中,我们创建了两个 `Time` 对象 `t1` 和 `t2`,然后将它们相加得到了一个新的 `Time` 对象 `t3`,最后输出了 `t1 + t2 = t3` 的结果。