用c++实现一个日期类,可实现:
1.日期加或减一个天数,之后的日期;
2.两个日期之间差多少天;
3.对日期进行++(后置) 或 – (后置) 操作;
4.对日期进行++(前置) 或 – (前置) 操作;
以下源程序:
#include <iostream>
#include <stdlib.h>
using namespace std;
class Date
{
friend void Print_Date(const Date&d);
public:
Date(int year = 2001, int month = 1, int day = 1)
:_year(year)
, _month(month)
, _day(day)
{}
bool Date::operator==(const Date& d)
{
return (_year == d._year && _month == d._month && _day == d._day);
}
Date operator+(int day) //重载+
{
Date temp(*this);
if (day < 0)
{ //考虑到date + -50这种情况,直接调用date - 50的函数
day = -day;
return temp - day;
}
temp._day += day;
while (temp._day > GetDaysInMonth(temp._year, temp._month))
{
temp._day = temp._day - GetDaysInMonth(temp._year, temp._month);
temp._month += 1;
if (temp._month > 12)
{
temp._year += 1;
temp._month = 1;
}
}
return temp;
}
bool operator<(const Date& d)
{
if ((this->_year < d._year) ||
((this->_year == d._year) && (this->_month < d._month)) ||
(this->_year == d._year) && (this->_month == d._month) && (this->_day == d._day))
return true;
return false;
}
int operator-(const Date& date)//重载 - (两日期相减)
{
Date maxDate(*this);
Date minDate(date);
int days = 0;
while (1)
{
if (maxDate < minDate) //考虑到小日期减大日期
{
maxDate = date;
minDate = *this;
}
if (minDate + days == maxDate)
break;
days++;
}
return days;
}
Date operator-(int day)
{
Date temp(*this);
temp._day -= day;
while (temp._day <= 0)
{
if (temp._month == 1)
{
temp._year--;
temp._month = 12;
}
else
{
temp._month--;
}
temp._day += GetDaysInMonth(temp._year, temp._month);
}
return temp;
}
Date operator=(const Date& d) //重载=
{
this->_year = d._year;
this->_month = d._month;
this->_day = d._day;
return *this;
}
void Print_Date()
{
cout << this->_year << "-" << this->_month << "-" << this->_day << endl;
}
Date operator--(int)//重载后置--
{
Date temp(*this);
*this = *this - 1;
return temp;
}
Date& operator--()//前置--形如--A
{
return (*this = *this - 1);
}
Date& operator++()//前置++形如++A
{
return (*this = *this + 1);
}
Date operator++(int)//重载后置++
{
Date temp(*this);
*this = *this + 1;
return temp;
}
private:
int _year;
int _month;
int _day;
bool IsLeap(int year) //判断是否为闰年
{
if (((0 == (year % 4)) && (0 != year % 100))
|| (0 == (year % 400)))
return true;
return false;
}
int GetDaysInMonth(int year, int month) //获取月的天数
{
int months[13] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
if (IsLeap(year))
{
months[2] = 29;
}
return months[month];//返回月天数
}
};
int main()
{
//测试 + 天数和 A++操作 A--操作
Date A(2017, 3, 27);
A = A + 1234;
A++;
//A.Print_Date();//经测试正确
A--;
A.Print_Date();//经测试正确
//测试 相差 天数
Date B(2017, 3, 27);
Date C(2028, 12, 3);
int ret = 0;
ret = C - B;
cout << ret << endl;//经测试正确
//测试日期--
Date D(2017, 3, 27);
++D;
D.Print_Date();//经测试正确
--D;
D.Print_Date();//经测试正确
system("pause");
return 0;
}
测试的结果: