日付計算機の実装
3143 ワード
#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;
}
1つのクラスには6つの基本的なメンバー関数が含まれています.その中で最も主要なのはコンストラクション関数、コピーコンストラクション関数、解析関数、付与演算子のリロードです.書かないと、システムにはデフォルトでこれらの関数がありますが、newで空間を開くことに関連する場合は、deleteが開いた空間を書く必要があります.そうしないと、メモリが漏洩します.