日期减日期 不复用运算符重载

#include 
#include 
using namespace std;

class Date
{
public:
	Date(int year = 1, int month = 1, int day = 1) //成员函数的声明和定义
	{
		_year = year;
		_month = month;
		_day = day;
	}

	int operator-(const Date& d);  // d1-d2  运算符重载的申明

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


//获取某年某月的天数
int GetMonthDay(int year, int month)
{
	static int days[13] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 };
	int day = days[month];
	if (2 == month
		&& ((0 == year % 4 && year % 100 != 0) || (0 == year % 400)))
	{
		day += 1;
	}
	return day;
}

int GetYearDaysNum(int year1, int year2) //获取整年的天数
{
	int max = year1;
	int min = year2;
	if (year1 < year2)
	{
		max = year2;
		min = year1;
	}

	int yearNum = abs(max - min);
	int n = 0;
	for (int i = min; i < max; i++)
	{
		if ((0 == i % 4) && (i % 100 != 0) || (0 == i % 400))
		{
			++n;
		}
	}
	return yearNum * 365 + n;
}

int GetDaysNum(int year, int month, int day) //获取非整年的天数
{
	int tmp = 0;
	for (int i = 1; i < month; i++)
	{
		tmp += GetMonthDay(year, i);
	}
	return tmp + day - 1;
}


int Date::operator-(const Date& d) //成员函数的定义
{
	int ret = GetYearDaysNum(this->_year, d._year);
	int ret1 = GetDaysNum(this->_year, this->_month, this->_day);
	int ret2 = GetDaysNum(d._year, d._month, d._day);

	// *this
	if ((_year < d._year)
		|| (_year == d._year && _month < d._month)
		|| (_year == d._year && _month == d._month && _day < d._day))
		return -(ret + ret2 - ret1); //加上大的非整年(后面的非整年),减去小的非整年(前面的非整年)

	// *this>=d
	return ret + ret1 - ret2; //加上大的非整年(后面的非整年),减去小的非整年(前面的非整年)

}


int main()
{
	Date d1(1995, 9, 1);
	Date d2(2100, 8, 15);

	cout << (d2 - d1) << endl;
	//  d2.operator-(const Date& d);

	return 0;
}

你可能感兴趣的:(c++)