打卡 C++类与对象定义一个日期类 N天以后 - C/C++ 操作符重载

发布时间 2023-04-27 23:54:48作者: 起名字真难_qmz

改造练习13-1(日复一日)中的Date类并提交,使其可以与一个整数n相加或相减,得到该日期N天后/前的日期。

提示:

  1. 请参考题目(日复一日)中的Date类实现;
  2. 注意考虑闰月;
  3. 整数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;
};