// 设计类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;
}
设计类CDate以满足:输出年月日日期格式;输入的日期加1;设置日期(参考清华版李春葆C++书籍)
最新推荐文章于 2023-01-09 21:50:35 发布