C++ 1 #include<iostream> 2 #include<ctime> 3 using namespace std; 4 int day_tab[2][12]={{31,28,31,30,31,30,31,31,30,31,30,31},{31,28,31,30,31,30,31,31,30,31,30,31}}; 5 class Date 6 { 7 int year; 8 int month; 9 int day; 10 public: 11 Date()//默认构造函数:获取当前日期 12 { 13 char tmpbuf[10]; 14 _strdate(tmpbuf);//_strdate定义在ctime头文件中,获取当前日期,_strdate(date)//初始化05_23_13位 15 month=(tmpbuf[0]-'0')*10+(tmpbuf[1]-'0');//统统减'0',把char转为int,2*10+3,0*10+5 16 day=(tmpbuf[3]-'0')*10+(tmpbuf[4]-'0');//2*10+3 17 year=2000+(tmpbuf[6]-'0')*10+(tmpbuf[7]-'0');//2000+1*10+3 18 } 19 Date(int y1,int m1,int d1)//重载构造函数 20 { 21 year=y1; 22 month=m1; 23 day=d1; 24 } 25 void dispdate()//输出日期 26 { 27 cout<<year<<"."<<month<<"."<<day<<endl; 28 } 29 int operator-(Date d1)//重载减号运算符 30 { 31 return (dton(*this)-dton(d1));//调用函数dton();dton(*this)返回调用后的值,dton(d1)刚开始的值 32 } 33 int isleap(int y)//判断是否为闰年 34 { 35 return ((y%4==0&&y%100!=0)||year%400==0);//布尔值 36 } 37 int dton(Date &d) 38 { 39 int y1,m1,days=0; 40 for(y1=1;y1<d.year;y1++) 41 if(isleap(y1)) 42 days+=366; 43 else 44 days+=365; 45 for(m1=0;m1<d.month-1;m1++) 46 if(isleap(d.year)) 47 days+=day_tab[1][m1]; 48 else 49 days+=day_tab[0][m1]; 50 days+=d.day; 51 return days; 52 } 53 }; 54 void main() 55 { 56 Date odate(2007,3,5),cdate; 57 cout<<"以前日期:"; 58 odate.dispdate(); 59 cout<<"今日日期:"; 60 cdate.dispdate(); 61 cout<<"相距天数:" 62 <<(cdate-odate)<<endl; 63 system("pause"); 64 }
转载于:https://www.cnblogs.com/herizai/archive/2013/05/23/3095456.html