用c++编写一个日期类(Time)并在类外编写一个判断两个日期是否为一年的函数
时间: 2024-02-25 20:55:58 浏览: 20
好的,下面是用C++编写的日期类(Time)以及判断两个日期是否为一年的函数:
```cpp
#include <iostream>
using namespace std;
class Time {
private:
int year;
int month;
int day;
public:
Time(int y, int m, int d) : year(y), month(m), day(d) {}
int getYear() const {
return year;
}
int getMonth() const {
return month;
}
int getDay() const {
return day;
}
};
bool isSameYear(const Time& t1, const Time& t2) {
return t1.getYear() == t2.getYear();
}
int main() {
Time t1(2021, 10, 1);
Time t2(2022, 1, 1);
Time t3(2021, 11, 1);
if (isSameYear(t1, t2)) {
cout << "t1 and t2 are in the same year" << endl;
} else {
cout << "t1 and t2 are not in the same year" << endl;
}
if (isSameYear(t1, t3)) {
cout << "t1 and t3 are in the same year" << endl;
} else {
cout << "t1 and t3 are not in the same year" << endl;
}
return 0;
}
```
在上面的代码中,我们定义了一个日期类Time,它包含了年、月、日三个私有成员变量,并且提供了相应的公有成员函数来获取这些变量的值。然后我们在类外编写了一个判断两个日期是否为一年的函数isSameYear,它接受两个Time对象作为参数,并且比较它们的年份是否相同。在main函数中,我们创建了三个Time对象,并且调用isSameYear函数来判断它们是否为同一年。