#include<iostream>
using namespace std;
//构造
class Date {
public:
//构造
Date(int year, int month, int day)
: _year(year)
, _month(month)
, _day(day)
{
if (year < 0 || month < 0 || day < 0 || month > 12 || day > 31)
{
_year = 1900;
_month = 1;
_day = 1;
}
cout << "Date(int, int, int):"<< endl;
}
//拷贝构造
Date(const Date& d)
: _year(d._year)
, _month(d._month)
, _day(d._day)
{
cout <<_year << endl;
cout <<_month << endl;
cout <<_day << endl;
}
//析构
~Date()
{
}
//运算符重载
//=
Date& operator=(const Date& d)
{
if (this != &d)
{
_year = d._year;
_month = d._month;
_day = d._day;
}
return *this;
}
//==判断两个日期是否相等
bool operator==(const Date& d)
{
return _year == d._year &&
_month == d._month &&
_day == d._day;
}
//!=判断两个日期是否不等
bool operator!=(const Date& d)
{
return !(*this == d); //==是重载运算符
}
int GetMonthday(int year, int month) //一个月有几天
{
int monthofday[] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
if (month != 2)
{
return monthofday[month];
}
else
{
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0)
{
return monthofday[2] + 1;
}
else
return monthofday[month];
}
}
//求当前日期第days天后是哪一天
Date operator+(const int days)
{
Date tmp(*this);
tmp._day += days;
while (tmp._day > GetMonthday(tmp._year, tmp._month))
{
tmp._day -= GetMonthday(tmp._year, tmp._month);
tmp._month++;
if (tmp._month > 12)
{
tmp._month = 1;
tmp._year++;
}
}
return tmp;
}
//求当前日期第days天前是哪一天
Date operator-(const int days)
{
Date tmp(*this);
tmp._day -= days;
while (tmp._day < 0)
{
tmp._day += GetMonthday(tmp._year, tmp._month);
tmp._month--;
if (tmp._month < 1)
{
tmp._month = 12;
tmp._year--;
}
}
return tmp;
}
//前置++
Date& operator++()
{
if (_day == 30 && _month == 12)
{
_year++;
_month = 1;
_day = 1;
}
else if (_day == 30)
{
_month++;
_day = 1;
}
else
_day += 1;
return (*this);
}
//后置++
Date& operator++(int)
{
Date tmp(*this);
_day += 1;
return tmp;
}
// 求两个日期之间的差值
int operator-(const Date& d)
{
return abs((_year - d._year) * 365 + (_month - d._month) * 30 + _day - d._day);
}
private:
int _year;
int _month;
int _day;
};
int main()
{
Date d(2018, 1, 29);
Date d1(2017, 5, 6);
Date d3 = d1 + 999;
//d.operator=(d1);
//++d1;
//d1 = d1 + 450;
int y = d - d1;
cout << y;
system("pause");
return 0;
}
C++日期类
最新推荐文章于 2024-02-02 15:05:15 发布