设计一个日期类,包含以下功能: 1、只能通过传入年月日初始化。 2、可以加上一个数字n,返回一个该日期后推n天之后的日期。

#include<iostream>
#include <cstdio>
using namespace std;
class Data
{
private:
	int m_year;
	int m_month;
	int m_day;
public:
	Data() :m_year(2019), m_month(9), m_day(2)
	{
	}
	Data(int year, int month, int day) :m_year(year),
		                  m_month(month), m_day(day)
	{
	}
	int getyear()
	{
		return m_year;
	}
	void setyear(int year)
	{
		if (year > 0 && year <= 2019)
			this->m_year = year;
		else
			year = -1;
	}
	int getmonth()
	{
		return m_month;
	}
	void setmonth(int month)
	{

		if (month > 0 && month <= 12)
			this->m_month =  month;
		else
			month =  -1;

	}
	int getday()
	{
		return m_day;
	}
	void setday(int day)
	{
		if (day > 0 && day <= 31)
			this ->m_day =  day;
		else
			day = -1;
	}

	void getNData(int n)
	{
		switch (getmonth())
		{
		case 1:
		case 3:
		case 5:
		case 7:
		case 8:
		case 10:
		case 12:
			for (int i = 0; i < n;i++)
			{
				if (this->getday() != 31)
				{
					this->setday(this->getday() + 1);
				}
				else if (this->getmonth() == 12)
				{
					this->setyear(this->getyear() + 1);
					this->setmonth(1);
					this->setday(1);
				}
				else
				{
					this->setmonth(this->getmonth() + 1);
					this->setday(1);
				}
			}
			break;
		case 4:
		case 6:
		case 9:
		case 11:
			for (int i = 0; i < n;i++)
			{
				if (this->getday() != 30)
				{
					this->setday(this->getday() + 1);
				}
				else
				{
					this->setmonth(this->getmonth() + 1);
					this->setday(1);
				}
			}
			break;
		case 2:
			for (int i = 0; i < n;i++)
			{
				if ((this->getyear() % 4 == 0 && this->getyear() % 100 != 0) || this->getyear() % 400 == 0)
				{
					if (this->getday() != 29)
					{
						this->setday(this->getday() + 1);
					}
					else
					{
						this->setmonth(this->getmonth() + 1);
						this->setday(1);
					}
				}
				else
				{
					if (this->getday() != 28)
					{
						this->setday(this->getday() + 1);
					}
					else
					{
						this->setmonth(this->getmonth() + 1);
						this->setday(1);
					}
				}
			}
			break;	
		}
	}
	void show()
	{
		cout << m_year << " " << m_month << " " << m_day << endl;
	}

};
int main()
{
	Data P1 (2018,12,31);
	P1.getNData(5);
	P1.show();
	system("pause");
	return 0;
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值