#include<stdlib.h>
#include<string.h>
using namespace std;
class Date
{
public:
Date(int year = 1900, int month = 1, int day = 1)
{
if (year <= 0 || month <= 0 || day <= 0 || day > getDay(year, month)) //判断日期是否有效
{
cout << "日期无效" << endl;
cout << "日期重置为1900-1-1" << endl;
_year = 1900;
_month = 1;
_day = 1;
}
else
{
_year = year;
_month = month;
_day = 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 (month == 2)
{
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) //判断是否为闰年
++day;
}
return day;
}
// 日期+=天数
Date& operator+=(int day) //可以返回值也可以返回引用,但返回引用效率高
{
if (day < 0) //判断日期是否为负
{
return *this -= -day;
}
_day += day; //日期累加
while (_day>getDay(_year, _month)) //判断日期是否溢出
{
_day -= getDay(_year, _month); //减去当月天数
_month++; //月份进位
if (_month == 13) //判断月份是否溢出
{
_month = 1;
++_year; //年份进位
}
}
return *this;
}
// 日期+天数
Date operator+(int day) //只能返回值
{
Date tmp(*this);
return tmp += day;
}
// 日期-天数
Date operator-(int day)
{
Date tmp(*this); //拷贝构造一个临时对象
return tmp -= day;
}
// 日期-=天数
Date& operator-=(int day)
{
if (day < 0)
{
return *this += -day;
}
_day -= day;
while (_day <= 0); //判断是否需要回退
{
--month; // 回退到上一个月
if (_month == 0)
{
--_year; //年份回退
_month = 12;
}
_day += getDay(_year, _month);
}
return *this;
}
// 前置++
Date& operator++()
{
return *this += 1; //调用+=函数
}
// 后置++
Date operator++(int) //int参数没有实际意义 作为标记使用
{
Date tmp(*this);
*this += 1;
return tmp; //修改前的内容以值的形式返回
}
// 后置-
Date operator--(int)
{
Date tmp(*this);
*this -= 1;
return tmp;
}
// 前置--
Date& operator--()
{
return *this -= 1;
}
// >运算符重载
bool operator>(const Date& d)
{
if (_year > d._year)
{
return true;
}
else if (_year == d._year)
{
if (_month > d._month)
{
return true;
}
else if (_month == d._month)
{
if (_day > d._day)
{
return true;
}
}
}
return false;
}
// ==运算符重载
bool operator==(const Date& d)
{
return _year == d._year
&& _month == d._month
&& _day == d._day;
}
// >=运算符重载
inline bool operator >= (const Date& d)
{
if (*this > d || *this == d)
return true;
else
return false;
}
// <运算符重载
bool operator < (const Date& d)
{
if (_year < d._year)
{
return true;
}
else if (_year == d._year)
{
if (_month < d._month)
{
return true;
}
else if (_month == d._month)
{
if (_day < d._day)
{
return true;
}
}
}
return false;
}
// <=运算符重载
bool operator <= (const Date& d)
{
if (*this < d || *this == d)
return true;
else
return false;
}
// !=运算符重载
bool operator != (const Date& d)
{
if (*this == d)
{
return false;
}
else
{
return true;
}
}
// 日期-日期 返回天数
int operator-(const Date& d)
{
Date max = *this;
Date min = d;
int flag = 1;
if (min > max)
{
min = *this;
max = d;
flag = -1;
}
int day = 0;
while (min < max)
{
++day;
++min:
}
return day*flag;
}
//void printDate()
//{
// cout << _year << "-" << _month << "-" << _day << endl;
// }
private:
int _year;
int _month;
int _day;
};
【C++】日期类的实现
最新推荐文章于 2024-02-02 15:05:15 发布