1. 程式人生 > >c++ 設計一個CDate類

c++ 設計一個CDate類

要求滿足如下要求:有帶參建構函式;可設定日期;可執行日期加一天的操作;有輸出操作(用日/月/年格式輸出日期。

#include <iostream>
#include <iomanip>
using namespace std;
class CDate
{
public:
CDate(int nYear = 0, int nMon = 0, int nDay = 0);
bool SetData(int nYear, int nMon = 0, int nDay = 0);
bool AddDay();
void PrintData();
private:
bool IsTrue();
int m_nYear;
int m_nMonth;
int m_nDay;
};
CDate::CDate(int nYear, int nMon, int nDay)
:m_nYear(nYear), 
m_nMonth(nMon),
m_nDay(nDay)
{}
bool CDate::IsTrue()
{
//將每一個月的天數儲存在陣列
static unsigned char days[12]
= { 31, 0, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
//判斷月份是否有效(小於1,大於12都是無效月份)
if (m_nMonth >= 13 || m_nMonth <= 0)
{
return false;
}
// 判斷年份是否為閏年
if (m_nYear > 0 && m_nYear % 400 == 0 ||
m_nYear % 4 == 0 && m_nYear % 100 != 0)
{
days[1] = 29;
}
else
days[1] = 28;
//判斷天數是否在對應月份的天數的範圍內
if (m_nDay > days[m_nMonth - 1] || m_nDay <= 0)
{
return false;
}


return true;
}
bool CDate::SetData(int nYear, int nMon, int nDay)
{
m_nYear = nYear;
m_nMonth = nMon;
m_nDay = nDay;
return IsTrue();
}
void CDate::PrintData()
{
if (IsTrue())
{
cout << " { "<< setw(2) << m_nDay << '/'
<< setw(2) << m_nMonth << '/'
<< setw(4) << m_nYear << " } " << endl;
}
else
{
cout << "無效的日期" << endl;
}
}
bool CDate::AddDay()
{
if (!IsTrue())
{
return false;
}
m_nDay++;
if (!IsTrue())
{
m_nDay = 1;
m_nMonth++;
if (!IsTrue())
{
m_nMonth = 1;
m_nYear++;
}
}
return true;
}
int main()
{
CDate date;
int nDay = 0, nMon = 0, nYear = 0;
for (;;)
{
cout << "請輸入年月日:";
cin >> nYear >> nMon >> nDay;
while (!date.SetData(nYear, nMon, nDay))
{
cout << "輸入的日期有誤,請重新輸入";
cin >> nYear >> nMon >> nDay;
}
for (int i = 1; i < 50; i++)
{
date.AddDay();
date.PrintData();
}
}
system("pause");
return 0;
}