Design date, the date will be determined to push back the date n days

Design a date class, includes the following features:
1, can only be initialized by passing date.
2, a number n may be added, after a return to the date after n days pushing date.
Methods: date to achieve cumulative monthly

//建立Date.h文件
#pragma once
#include <iostream>
using namespace std;

typedef unsigned int uint;

class Date{
	uint m_year;
	uint m_month;
	uint m_day;
public:
	Date(uint y, uint m, uint d) :
		m_year(y),
		m_month(m),
		m_day(d)
	{

	}

	Date operator + (uint delay) const;//保证this不被改变,对 + 运算符进行重载
	friend ostream & operator << (ostream &os, Date &d);//对输出运算符 << 重载
};

//建立Date.cpp文件
#include "Date.h"

static uint getMonthDay(uint y, uint m){//计算某年的某月有多少天
	if (m > 12 || m == 0){
		return 0;
	}
	if (m == 4 || m == 6 || m == 9 || m == 11){
		return 30;
	}
	else if (m == 2){
		return 28 + (y % 400 == 0 || (y % 4 == 0 && y % 100));
	}
	else{
		return 31;
	}
}

ostream & operator << (ostream &os, Date &d){
	os << d.m_year << '-' << d.m_month << '-' << d.m_day << endl;
	return os;
}

Date Date::operator + (uint delay) const{//进行一月一月地跳转
	Date res = *this;//存放初始日期
	uint tmp;

	tmp = getMonthDay(res.m_year, res.m_month);

	while (delay >= tmp){//当增加的天数大于等于一个月的天数,进入循环
		delay -= tmp;
		res.m_month++;
		if (res.m_month > 12){//当月数增加超过12
			res.m_month = 1;//将年增加一,将月数调整为1
			res.m_year++;
		}
		tmp = getMonthDay(res.m_year, res.m_month);
	}//直到delay的天数不够一个月,跳出循环
	res.m_day += delay;//将剩余天数加在天数上
	if (res.m_day > tmp){//天数超过此月的天数
		res.m_day -= tmp;//月数加一,天数减去此月的天数
		res.m_month++;
	}
	return res;
}

//建立main.cpp文件
#include "Date.h"

int main(){
	Date test(2019, 9, 7);

	cout << (test + 1000) << endl;
	system("pause");
	return 0;
}
Published 77 original articles · won praise 23 · views 7554

Guess you like

Origin blog.csdn.net/Hots3y/article/details/100610196