打卡 C++类与对象定义一个日期类 N天以后 - C/C++ 操作符重载
改造练习13-1(日复一日)中的Date类并提交,使其可以与一个整数n相加或相减,得到该日期N天后/前的日期。
提示:
- 请参考题目(日复一日)中的Date类实现;
- 注意考虑闰月;
- 整数n的取值范围为[1,10000]。
裁判测试程序样例:
#include <iostream>
#include <string>
#include <assert.h>
using namespace std;
//在此处补充Date类的定义
int main()
{
int y, m, d;
cin >> y >> m >> d;
Date d1(y,m,d);
int n;
cin >> n;
cout << d1.toText() << " + " << n << " = " << (d1 + n).toText() << endl;
cout << d1.toText() << " - " << n << " = " << (d1 - n).toText() << endl;
return 0;
}
输入样例:
2022 8 31
2
说明:意为求2022年8月31日的后两天和前两天的日期。
输出样例:
2022-8-31 + 2 = 2022-9-2
2022-8-31 - 2 = 2022-8-29
思路:需要设置错误检测,闰年判断,与获取并修改日期系统。
代码实现:
class Date {
public:
Date(int y, int m, int d) : year(y), month(m), day(d) {
assert(month >= 1 && month <= 12 && day >= 1 && day <= getDays());
}
Date operator+(int n) {
if(n<1||n>10000) break;
int days = day + n;
int curYear = year;
int curMonth = month;
while (days > getDays()) {
days -= getDays();
curMonth++;
if (curMonth > 12) {
curMonth = 1;
curYear++;
}
}
return Date(curYear, curMonth, days);
}
Date operator-(int n) {
if(n<1||n>10000) break;
int days = day - n;
int curYear = year;
int curMonth = month;
while (days <= 0) {
curMonth--;
if (curMonth == 0) {
curMonth = 12;
curYear--;
}
days += getDays(curYear, curMonth);
}
return Date(curYear, curMonth, days);
}
string toText(){
return to_string(year) + "-" + to_string(month) + "-" + to_string(day); //输出运算符重载
}
int getDays(int y = 0, int m = 0) {
if (y == 0) y = year;
if (m == 0) m = month;
if (m == 2) {
if (isLeapYear(y)) return 29;
else return 28;
} else if (m <= 7) {
if (m % 2 == 1) return 31;
else return 30;
} else {
if (m % 2 == 0) return 31;
else return 30;
}
}
bool isLeapYear(int y) {
if (y % 4 == 0 && y % 100 != 0 || y % 400 == 0) return true;
else return false;
}
private:
int year,month,day;
};
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!