实现一个日期计算器
2017-10-20 20:40
281 查看
#include <iostream>using namespace std;class Date{public: Date(int year = 1900,int month = 1,int day = 1) { //判断输入是否正确 if((year<1900)||(month<1)||(month>12)||(day<1)||(day>GetMonthDay(year,month))) { cout<<"输入有误"<<endl; exit(0); } _year = year; _month = month; _day = day; } Date(Date& d) { _year = d._year; _month = d._month; _day = d._day; } ~Date() { //cout<<"析构函数"<<endl; } Date& operator=(Date& d) { _year = d._year; _month = d._month; _day = d._day; return *this; } int GetMonthDay(int year,int month) { if(IsLeapYear(year) && (month == 2)) //判断是否为闰年 { return 29; } else { int mon[] = {31,28,31,30,31,30,31,31,30,31,30,31}; return mon[month-1]; } } bool IsLeapYear(int year) { return (((year%400) ==0 ) || (((year%4) == 0) && ((year%100) == 0))); } Date CountDate(int num) { _day += num; if(_day > 0) { while(_day>GetMonthDay(_year,_month)) { _day -= GetMonthDay(_year,_month); _month++; if(_month>12) { _year++; _month -= 12; } } return *this; } else { while(_day<=0) { _month--; if(_month<1) { _year--; _month += 12; } _day += GetMonthDay(_year,_month); } return *this; } } int operator-(Date& d) { int count = 0; if((_month == d._month)&&(_year == d._year)) { count = _day - d._day; return count; } count = _day + GetMonthDay(d._year,d._month) - d._day; _month--; while((_month != d._month)||(_year != d._year)) { if(_month<1) { _year--; _month += 12; } if((_month != d._month)||(_year != d._year)) { count += GetMonthDay(_year,_month); _month--; } } return count; } Date& GetDate() { cin>>_year>>_month>>_day; return *this; } void Display() { cout<<_year<<"-"<<_month<<"-"<<_day<<endl; }private: int _year; int _month; int _day;};void Test1(){ cout<<"**************************"<<endl; cout<<"********日期计算器********"<<endl; cout<<"**************************"<<endl; cout<<endl; while(1) { int n = 0; cout<<"*1.计算日期推移天数 *2.计算日期间相差天数 *3.退出"<<endl; cout<<"输入你的选择: "; cin>>n; switch(n) { case 1: { int day = 0; Date d; Date dis; cout<<"请输入日期和天数:"<<endl; d.GetDate(); cin>>day; dis = d.CountDate(day); dis.Display(); break; } case 2: { Date d1; Date d2; cout<<"请输入日期:"<<endl; d1.GetDate(); d2.GetDate(); cout<<d1-d2<<endl; break; } case 3: { exit(0); } } }}int main(){ Test1(); return 0;}一个类包含6个基本的成员函数,其中最主要的是构造函数,拷贝构造函数,析构函数,赋值运算符的重载,若不写,系统默认有这些函数,但如果涉及到用new开辟空间,则需要写上析构函数等来delete开辟的空间,否则就会出现内存泄露。
本文出自 “敲完代码好睡觉zzz” 博客,请务必保留此出处http://2627lounuo.blog.51cto.com/10696599/1716519
相关文章推荐
- 类实现一个简单的日期计算器
- 实现一个日期计算器
- 类实现一个简单的日期计算器
- 使用comet架构实现了一个基于网页的视频监控prototype!!!!哇哈哈庆祝一下
- 实现一个栈,Push,Pop,Min,并且保证时间复杂度为O(1)
- 400多行Python代码实现了一个FTP服务器
- 一个实现了和数据库打交道的源文件(组装sql语句版)
- [UWP]附加属性2:实现一个Canvas
- 通过实现一个 TableView 来理解 iOS UI 编程
- 一个简单实现apk推广并静默安装的样本分析
- Java实现一个HashMap
- 如何实现一个UI系统
- JAVA,结合Extjs4实现一个树
- 一个Spark推荐系统引擎的实现
- XMPP客户端关于用户组排序的一个可能的实现方法
- Android中使用Kotlin实现一个简单的登录界面
- 是一个工具 想C 实现一下
- 让枚举实现一个接口
- 写了一个作业 实现用户登录和注册的脚本,初学者写的不好,记录一下我的学习经历
- 利用Redis实现限制一个用户只能在一个地点登陆