学完前面的东西,现在来具体应用一下
写一个日期类,具体功能如下:
bool LeapYear(int year)//判断是不是闰年
int MonthDay(int year, int month)//每月天数的判断
Date operator++()//前置++
Date operator++(int)//后置++
Date operator--()//前置--
Date operator--(int)//后置--
Date operator+(int days)//当前日期加上days天前的日期
Date operator-(int days)//当前日期减去days天前的日期
Date operator-(int days)//两个日期相差多少天
Date*operator&()//取地址运算符重载
Date& operator=(const Date&d)//赋值运算符重载
int operator-(const Date&d);
bool operator>(const Date&d)
bool operator<(const Date&d)
bool operator==(const Date&d)
bool operator!=(const Date&d)
具体实现如下:
class Date
{
public:
Date()
{}
Date(int year, int month, int day)
: _year(year)
, _month(month)
, _day(day)
{
if ((year < 1) && (month<1 && month>12) && (day<1 && day>MonthDay(year, month)))
{
cout << "日期非法" << endl;
}
}
//判断是不是闰年
bool LeapYear(int year)
{
if (0 == year / 4 && 0 != year / 100 || 0 == year / 400)
{
return true;
}
else
{
return false;
}
}
//每月天数的判断
int MonthDay(int year, int month)
{
int MonDay[] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
if (2 == month&&LeapYear(year))
{
MonDay[month] += 1;
}
return MonDay[month];
}
//前置++
Date operator++()
{
_day += 1;
return *this;
}
//后置++
Date operator++(int)
{
Date temp = *this;
_day += 1;
return temp;
}
//前置--
Date operator--()
{
_day -= 1;
return *this;
}
//后置--
Date operator--(int)
{
Date temp = *this;
_day += 1;
return temp;
}
//重载取地址符号
Date*operator&()
{
return this;
}
//实现连续赋值
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;
}
//当前日期加上days天后的日期
Date operator+(int days)
{
if (days < 0)
{
cout << "error" << endl;
}
int MonDay = 0;
Date tmp(*this);
tmp._day += days;
while (tmp._day>(MonDay = MonthDay(tmp._year, tmp._month)))
{
tmp._day -= MonDay;
tmp._month+=1;
if (tmp._month > 12)
{
tmp._year += 1;
tmp._month = 1;
}
}
return tmp;
}
//当前日期减去days天前的日期
Date operator-(int days)
{
if (days < 0)
{
cout << "error" << endl;
}
Date tmp(*this);
tmp._day -= days;
while (tmp._day <= 0)
{
tmp._month -= 1;
if (0 == tmp._month)
{
tmp._year -= 1;
tmp._month = 12;
}
tmp._day += MonthDay(tmp._year, tmp._month);
}
return tmp;
}
//计算两个日期相差多少天
int operator-(const Date&d)
{
Date minDate(*this);
Date maxDate(d);
if (minDate > maxDate)
{
minDate = d;
maxDate = *this;
}
int count = 0;
while (minDate != maxDate)
{
count++;
++minDate;
}
return count;
}
//判断两个日期的大小
bool operator>(const Date&d)
{
if (_year > d._year || _month > d._month || _day > d._day)
{
return true;
}
else
{
return false;
}
}
bool operator<(const Date&d)
{
if (_year < d._year || _month < d._month || _day < d._day)
{
return true;
}
else
{
return false;
}
}
private:
int _year;
int _month;
int _day;
};
int main()
{
Date d1(2018, 9, 11);
Date d2(d1);
Date d3;
d3 = d2 + 100;
return 0;
}
运行结果:
有点长慢慢看,收获会很大