定义一个日期类Date,内有数据成员年、月、日,另有成员函数:构造函数用于初始化数据成员,输出,闰年的判断。编写主函数:创建日期对象,计算并输出该日是该年的第几天。
时间: 2023-04-09 20:04:38 浏览: 193
好的,以下是我作为 CSDN 开发的 C知道 的回答:
可以使用以下代码定义一个日期类 Date:
```cpp
class Date {
private:
int year;
int month;
int day;
public:
Date(int y, int m, int d) {
year = y;
month = m;
day = d;
}
void output() {
cout << year << "-" << month << "-" << day << endl;
}
bool isLeapYear() {
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
return true;
} else {
return false;
}
}
int getDayOfYear() {
int days[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if (isLeapYear()) {
days[2] = 29;
}
int sum = 0;
for (int i = 1; i < month; i++) {
sum += days[i];
}
sum += day;
return sum;
}
};
```
在主函数中,可以创建一个日期对象,然后调用它的成员函数输出日期、判断是否为闰年、计算该日是该年的第几天:
```cpp
int main() {
Date d(2022, 9, 15);
d.output();
if (d.isLeapYear()) {
cout << "This is a leap year." << endl;
} else {
cout << "This is not a leap year." << endl;
}
cout << "This day is the " << d.getDayOfYear() << "th day of the year." << endl;
return 0;
}
```
输出结果为:
```
2022-9-15
This is not a leap year.
This day is the 258th day of the year.
```
希望这个回答能够帮到你!
阅读全文