Date类的实现

代码实现

#include<iostream>
#include<stdlib.h>
using namespace std;


class   Date
{
public:
Date(int year = 1990, int month = 10, int day = 10)
{
if (!((year > 0) && (0 < month <= 12) && (0 < day < 31)))
{
_year = 1990;
_month = 10;
_day = 10;
}
else
{
_year = year;
_month = month;
_day = day;
}
}
friend ostream&operator<<(ostream&_cout, const Date& d);
bool Date::operator==(const Date& d)
{
return _year == d._year && _month == d._month && _day == d._day;
}
bool Date::operator!=(const Date& d)
{
return !(*this == d);
}
int Date::operator-(const Date& d)
{
int day = 0;
Date small(d);
Date big(*this);


if (*this < d)
{
small = *this;
big = d;
}
else
{
small = d;
big = *this;
}


while (small != big)
{
small++;
day++;
}
return day;
}


bool Date::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;
}
else
{
return false;
}
}
else
{
return false;
}
}
else
{
return false;
}
}
Date operator+(int days)
{
if (days < 0)
{
days = 0 - days;
}
_day = _day + days;
while (_day>(Getmonthdays(_year, _month)))
{
_day = _day - Getmonthdays(_year, _month);
_month++;
if (_month>11)
{
_month = 1;
_year++;
}
}
return *this;
}
Date operator-(int days)
{
if (days<0)
{
days = 0 - days;
}
days = (_day)-days;
while (days <= 0 && days<(Getmonthdays(_year, _month)))
{
days = days + Getmonthdays(_year, _month);
_month--;
if (_month <= 1)
{
_month = 12;
_year--;
}
}
_day = days;
return *this;
}


Date operator++()//前置加加
{
_day = _day++;
if (_day>Getmonthdays(_year, _month))
{
_day = _day - Getmonthdays(_year, _month);
_month++;
if (_month == 12)
{
_year++;
}
}
return  *this;
}
Date operator++(int)//后置加加
{
Date temp = *this;
++(*this);
return temp;
}
bool IsLeapyear(int year)
{
if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0))
{
return true;
}
return false;
}


~Date()
{


}
private:
int& Getmonthdays(int year, int month)
{
int temp;
int arr[] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
if (IsLeapyear(year) && month == 2)
{
temp = arr[month] + 1;
}
temp = arr[month];
return temp;
}
private:
int _year;
int _month;
int _day;
};




ostream&operator<<(ostream&_cout, const Date& d)
{
_cout << d._year << "-" << d._month << "-" << d._day << endl;
return _cout;
}
void FunTest()
{


Date d1(2017, 1, 1);
Date d2(2017, 2, 1);
cout << d1 + 20 << endl;
cout << d1 - 20 << endl;
cout << ++d1 << endl;
cout << d1++ << endl;
cout << d1 - d2 << endl;
}
int main()
{
FunTest();
system("pause");
return 0;
}


结果实现:




  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值