自己写的这个日期类实现了简单的一些日期可能会用到的功能,
比如加减某一个日期等等,详细的已在代码里面标注出来了。
#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 < 1900
||month < 1 || month > 12
|| day < 1 || day > GetMonthDay(year,month))
{
cout << "Invalid Date" << endl;
}
}
int GetMonthDay(int year, int month)
{
int monthArray[12] = { 31, 28, 31, 30, 31,
30, 31, 31, 30, 31, 30, 31 };
if (IsLeapYear(year)&&month==2)
{
return monthArray[month - 1] + 1;
}
return monthArray[month - 1];
}
bool IsLeapYear(int year)
{
return year % 400 == 0 || year % 4 == 0
&& year % 100 != 0;
}
Date operator+(int day) //加一个天数
{
Date tmp(*this);
tmp._day += day;
while (tmp._day > GetMonthDay(tmp._year,tmp._month))
{
tmp._day -= GetMonthDay(tmp._year, tmp._month);
if (tmp._month == 12)
{
tmp._year += 1;
tmp._month = 1;
}
else
{
tmp._month += 1;
}
}
return tmp;
}
Date& operator+=(int day)
{
this->_day += day;
while (this->_day > GetMonthDay(this->_year, this->_month))
{
this->_day -= GetMonthDay(this->_year, this->_month);
if (this->_month == 12)
{
this->_year += 1;
this->_month = 1;
}
else
{
this->_month += 1;
}
}
return *this;
}
Date operator-(int day) //减一个天数
{
Date tmp(*this);
tmp._day -= day;
while (tmp._day < 0)
{
if (tmp._month == 1)
{
tmp._year -= 1;
tmp._month = 12;
tmp._day += GetMonthDay(tmp._year, tmp._month);
}
else
{
tmp._month -= 1;
tmp._day += GetMonthDay(tmp._year, tmp._month);
}
}
return tmp;
}
Date operator++() //前置自增
{
*this += 1;
return *this;
}
bool operator==(const Date& d) //测试日期相等
{
return _year == d._year&&
_month == d._month&&
_day == d._day;
}
bool operator!=(const Date& d)
{
return !(_year == d._year&&
_month == d._month&&
_day == d._day);
}
bool operator<(const Date& d)
{
return !(_year < d._year&&
_month < d._month&&
_day < d._day);
}
int operator-(const Date& d) //一个日期减一个日期
{
Date tmp1 = d;
Date tmp2 = *this;
int count = 0;
if (tmp2 < tmp1)
{
Date rev;
rev = tmp2;
tmp2 = tmp1;
tmp1 = rev;
}
while (tmp2 != tmp1)
{
count++;
++tmp1;
}
return count;
}
void Display()
{
cout << _year << "-" << _month << "-" << _day << endl;
}
private:
int _year;
int _month;
int _day;
};
void Test1() //测试加减某一个天数
{
int day;
Date d1(2015,3,1);
d1.Display();
cin >> day;
//(d1 + day).Display();
(d1 - day).Display();
}
void Test2()
{
Date d1(2015, 2, 28);
//d1.Display();
Date d2(2015, 2, 28);
cout << (d1 != d2) << endl;
//(d1++).Display();
}
void Test3()
{
Date d1(2004, 2, 1);
Date d2(2004, 3, 1);
int ret = d1 - d2;
cout << ret << endl;
}
int main()
{
//Test1();
//Test2();
Test3();
return 0;
}
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。