实现一个日期计算器

#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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值