设计类CDate以满足:输出年月日日期格式;输入的日期加1;设置日期(参考清华版李春葆C++书籍)
2016-04-02 11:10
543 查看
// 设计类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; }
相关文章推荐
- C++中的输出格式 八进制 十进制 十六进制
- c++断言设置
- C++中构造函数或析构函数定义为private
- 第1周 C语言及程序设计初步 例程-7 问题求解方法——迭代
- C语言18个经典问题答录
- C++ 判断double变量是否为0
- [leetcode]326. Power of Three(c语言)
- 测试某一段程序运行时间的方法
- C++统计一个文件中每个数字字符(0~9)出现的次数
- C语言中的强符号和弱符号(变量篇)
- 第1周 C语言及程序设计初步 例程-6 用循环累加
- 一起talk C栗子吧(第一百三十五回:C语言实例--exec系列函数一)
- c++ 复数类
- 【笔试/面试】—— 奇葩 C/C++ 语法题
- C++类静态成员的使用
- C++开源库
- c++面试题
- C++智能指针与返回局部指针测试
- 第十七章,txt文件的写入和读取数据结合练习(C++)
- C++中const用法总结