【c++】实现日期类

#include <iostream>
using namespace std;

class Date
{
public:
	Date(int year=1900,int month=1,int day=1)
		:_year(year)
		,_month(month)
		,_day(day)
	{
		if(!(year>=0 && month>0 && month<13 && day>0 && day<=_GetDaysOfMonth(year,month)))
		{
			_year=1900;
			_month=1;
			_day=1;
		}
	}

	Date operator+(int days)
	{
		if(days<0)
			return *this-(0-days);
		Date temp(*this);
		temp._day +=days;

		int daysOfMonth;
		while(temp._day > (daysOfMonth = _GetDaysOfMonth(temp._year, temp._month)))
		{
			temp._day -=daysOfMonth;
			temp._month ++;
			if(temp._month >12)
			{
				temp._year +=1;
				temp._month =1;
			}
		}
		return temp;
	}

	Date operator-(int days)
	{
		if(days<0)
			return *this+(0-days);

		Date temp(*this);
		temp._day -=days;
		while(temp._day <=0)
		{
			temp._month --;
			if(0==temp._month )
			{
				temp._year -=1;
				temp._month= 12;
			}
			temp._day +=_GetDaysOfMonth(temp._year, temp._month);
		}
		return temp;
	}

	int operator-(const Date& d)
	{
		Date minDate(*this);
		Date maxDate(d);

		if(maxDate < minDate)
		{
			minDate=d;
			maxDate=*this;
		}

		int count=0;
		while(minDate < maxDate)
		{
			count++;
			++minDate;
		}

		return count;
	}

	bool IsLeap()
	{
		return _IsLeap(_year);
	}

	Date& operator++()
	{
		*this=*this+1;
		return *this;
	}

	Date& operator++(int)
	{
		Date temp(*this);
		++(*this);
		return temp;
	}

	Date& operator--()
	{
		*this=*this-1;
		return *this;
	}

	Date operator--(int)
	{
		Date temp(*this);
		--(*this);
		return temp;
	}

	 bool operator<(const Date& d)
	 {
		 if(_year<d._year || (_year==d._year && _month < d._month) ||
			(_year==d._year && _month==d._month && _day<d._day))
		 {
			 return true;
		 }
		 return false;
	 }

	 bool operator==(const Date& d)
	 {
		 return _year==d._year && _month==d._month && _day==d._day ;
	 }

	 bool operator!=(const Date& d)
	 {
		 return !(*this==d);
	 }

private:
	int _GetDaysOfMonth(int year,int month)
	{
		int days[]={0,31,28,31,30,31,30,31,31,30,31,30,31};
		if(2==month && _IsLeap(year))
			days[2]+=1;
		return days[month];
	}

	bool _IsLeap(int year)
	{
		if((0==year%4 && 0!=year%100)||
			(0==year%400))
		{
			return true;
		}
		return false;
	}

	friend ostream& operator<<(ostream& _cout,const Date& d)
	{
		_cout<<d._year<<"/"<<d._month<<"/"<<d._day;
		return _cout;
	}

private:
	int _year;
	int _month;
	int _day;
};

int main()
{
	Date d1(2018,6,24);
	Date d2(2018,1,1);
	cout<<d2-d1<<endl;
	cout<<d1-99<<endl;
	cout<<d1-999<<endl;
	cout<<d1+(-99)<<endl;
	return 0;
}

运行结果如下



猜你喜欢

转载自blog.csdn.net/lw__sunshine/article/details/81051348
今日推荐