#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
原文地址:http://2627lounuo.blog.51cto.com/10696599/1716519