1. 程式人生 > >設計類CDate以滿足:輸出年月日日期格式;輸入的日期加1;設定日期(參考清華版李春葆C++書籍)

設計類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;
}