功能:
日期加天数
日期减天数
日期减日期
#pragma once
#include <iostream>
using namespace std;
class Data
{
private:
int _year;
int _month;
int _day;
public:
//全缺省构造函数
Data(int year = 0, int month = 1, int day = 1);
//获得对应年月的天数
int getMonthDay(int year, int month);
//构造函数
Data(const Data& d);
//重载运算符
void operator=(const Data& d);
bool operator<(const Data& d) const;
bool operator==(const Data& d)const;
bool operator<=(const Data& d)const;
bool operator>(const Data& d)const;
bool operator>=(const Data& d)const;
//日期加减天数
void operator+=(int day);
Data operator+(int day)const;
void operator-=(int day);
Data operator-(int day)const;
//日期减日期
int operator-(const Data& d)const;
};
#include "Data.h"
Data::Data(int year , int month, int day ){
if (month <= 0 || month > 13 || day <= 0 || day > getMonthDay(year, month)) {
printf("日期非法!\n");
}
else {
_year = year;
_month = month;
_day = day;
}
}
int Data::getMonthDay(int year, int month) {
static int monthDay[13] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 };
if ((year % 4 == 0 && year % 100 != 0 || year % 400 == 0) && month == 2) {
return 29;
}
return monthDay[month];
}
bool Data::operator<(const Data& d) const {
if (_year < d._year) return true;
if (_year == d._year && _month < d._month)return true;
if (_year == d._year && _month == d._month && _day < d._day)return true;
return false;
}
bool Data::operator==(const Data& d)const {
return _year == d._year && _month == d._month && _day == d._day;
}
bool Data::operator<=(const Data& d)const {
return (*this) < d || (*this) == d;
}
bool Data::operator>(const Data& d)const {
return !(*this <= d);
}
bool Data::operator>=(const Data& d)const {
return !(*this < d);
}
Data::Data(const Data& d) {
_year = d._year;
_month = d._month;
_day = d._day;
}
void Data::operator=(const Data& d) {
_year = d._year;
_month = d._month;
_day = d._day;
}
void Data::operator+=(int day) {
_day += day;
while (_day > getMonthDay(_year, _month)) {
_day -= getMonthDay(_year, _month);
_month++;
if (_month == 13) {
_year++;
_month = 1;
}
}
}
Data Data::operator+(int day)const {
Data ret(*this);
ret += day;
return ret;
}
void Data::operator-=(int day) {
_day -= day;
while (_day <= 0) {
--_month;
if (_month == 0) {
_year--;
_month = 12;
}
_day += getMonthDay(_year, _month);
}
}
Data Data::operator-(int day)const {
Data ret(*this);
ret -= day;
return ret;
}
int Data::operator-(const Data& d)const {
Data max = *this;
Data min = d;
int flag = 1;
if (*this < d) {
max = d;
min = *this;
flag = -1;
}
int cnt = 0;
while (min < max) {
cnt ++ ;
min += 1;
}
return cnt*flag;
}