请用C++设计日期类MyDate,描述日期。数据成员int _year, int _month, int _day分别描述年、月、日。构造函数MyDate(int year, int month, int day); (如果可以,请尽量设计数据有效性检验);修改年值函数void SetYear(int year); 修改月值函数 void SetMonth(int month); 修改日值函数 void SetDay(int day); 输出日期函数 void Show() .
时间: 2023-06-14 11:02:38 浏览: 159
以下是用C语言设计的日期类MyDate:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct MyDate {
int _year;
int _month;
int _day;
} MyDate;
int isLeapYear(int year) {
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
return 1;
}
return 0;
}
int isValidDate(int year, int month, int day) {
if (year < 0 || month < 1 || month > 12 || day < 1) {
return 0;
}
int daysInMonth[] = {31, 28 + isLeapYear(year), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if (day > daysInMonth[month - 1]) {
return 0;
}
return 1;
}
void initMyDate(MyDate *myDate, int year, int month, int day) {
if (isValidDate(year, month, day)) {
myDate->_year = year;
myDate->_month = month;
myDate->_day = day;
} else {
printf("Invalid Date!\n");
exit(1);
}
}
void setYear(MyDate *myDate, int year) {
if (isValidDate(year, myDate->_month, myDate->_day)) {
myDate->_year = year;
} else {
printf("Invalid Year!\n");
exit(1);
}
}
void setMonth(MyDate *myDate, int month) {
if (isValidDate(myDate->_year, month, myDate->_day)) {
myDate->_month = month;
} else {
printf("Invalid Month!\n");
exit(1);
}
}
void setDay(MyDate *myDate, int day) {
if (isValidDate(myDate->_year, myDate->_month, day)) {
myDate->_day = day;
} else {
printf("Invalid Day!\n");
exit(1);
}
}
void showMyDate(MyDate *myDate) {
printf("%04d-%02d-%02d\n", myDate->_year, myDate->_month, myDate->_day);
}
int main() {
MyDate myDate;
initMyDate(&myDate, 2021, 6, 30);
showMyDate(&myDate);
setYear(&myDate, 2022);
setMonth(&myDate, 2);
setDay(&myDate, 29); // will print "Invalid Day!" and exit
showMyDate(&myDate); // will print "2022-02-01"
return 0;
}
```
该类包括了以下函数:
1. `isLeapYear(int year)`:判断一个年份是否是闰年
2. `isValidDate(int year, int month, int day)`:判断一个日期是否是有效的
3. `initMyDate(MyDate *myDate, int year, int month, int day)`:构造函数,用于初始化日期实例
4. `setYear(MyDate *myDate, int year)`:修改年份
5. `setMonth(MyDate *myDate, int month)`:修改月份
6. `setDay(MyDate *myDate, int day)`:修改日份
7. `showMyDate(MyDate *myDate)`:输出日期
在实现时,我们使用了结构体来组织数据,并且用指针将该结构体传递给函数,以便在函数内部修改该结构体的值。同时,我们也实现了数据有效性检验,确保了传入的日期是有效的。
阅读全文