设计类CDate以满足:输出年月日日期格式;输入的日期加1;设置日期(参考清华版李春葆C++书籍)

// 设计类CDate
// 满足:输出年月日日期格式;输入的日期加1;设置日期
#include<iostream>
using namespace std;

class CDate
{
private:
	int m_nDay;
	int m_nMonth;
	int m_nYear;
	bool IsLeapYear(); // 输入日期格式涉及到对闰年的判断
public:
	CDate();
	CDate(int, int, int);
	void Display();
	void AddDay();
	void SetDate(int, int, int);
	~CDate();
};
CDate::CDate(){} // 默认构造函数初始化
CDate::CDate(int year, int month, int day) // 带参构造函数初始化
{
	m_nDay=day;
	m_nMonth=month;
	m_nYear=year;
}
void CDate::Display() // 日期显示
{
	cout<<m_nYear<<"年"<<m_nMonth<<"月"<<m_nDay<<"日"<<endl;
}
void CDate::AddDay() // 当前日期加1
{
	if(IsLeapYear()) // 先判断是否是闰年
	{
		if(m_nMonth == 2 && m_nDay == 29)
		{
			m_nMonth++;
			m_nDay=1;
			return;
		}
	}
	else
	{
		if(m_nMonth == 2 && m_nDay == 28)
		{
			m_nMonth++;
			m_nDay=1;
			return;
		}
	}
	if(m_nMonth == 4 || m_nMonth == 6 || m_nMonth == 9 || m_nMonth == 11) // 再判断月份
	{
		if(m_nDay == 30)
		{
			m_nMonth++;
			m_nDay=1;
			return;
		}
	}
	else if(m_nMonth == 12)
	{
		if(m_nDay == 30)
		{
			m_nMonth=1;
			m_nDay=1;
			return;
		}
	}
	else
	{
		if(m_nDay == 31)
		{
			m_nMonth++;
			m_nDay=1;
			return;
		}
	}
	m_nDay++; // 普通年份普通月份普通日子就直接加1
}
void CDate::SetDate(int year, int month, int day) // 设置当前日期
{
	m_nYear=year;
	m_nMonth=month;
	m_nDay=day;
}
CDate::~CDate(){}
bool CDate::IsLeapYear() // 判读闰年
{
	bool bLeap;
	if((m_nYear%100 != 0 && m_nYear%4 == 0) || m_nMonth%400 ==0)
		bLeap=1;
	return bLeap;
}
int main()
{
	CDate date;
	int y, m, d;
	cout<<"请输入年月日:";
	cin>>y>>m>>d;
	date.SetDate(y, m, d);
	cout<<"当前输入日期:";
	date.Display();
	date.AddDay();
	cout<<"当前日期加1:";
	date.Display();
	return 0;
}

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值