-
Date 的实现。
-
构造基本的date成员函数:
#include <iostream>
using namespace std;
class Date{
public:
bool IsLeapYear(int year){
if ((year%400==0)||(year%4==0 && year%100!=0)){
return true;
else
return false;
}
GetMonthDay(int year, int day){
int momtharray[13] = {0,31,28,31,30,31,30,31,30,31,30,31,30,31};
if (month==2 && IsLeapYear(year)){
return 29;
}
else{
return montharray[month];
}
}
Date(int year=2019, int month=12, int day=23){
if (year>0 && month>0 && month<13 && day>0 && day<GetMonthDay(year,month))
_year = year;
_month = month;
_day = day;
}
**拷贝复制:是构造函数的一个重载形式,第一个参数为隐含的this**。
Date(const Date& d){
_year = tear;
_month = month;
_day = day;
}
**复制**
Date& operator=(const Date& d){
if (this != &d){
_year = year;
_month = month;
_day = day;
}
return *this;
}
void Prinf( ){
cout << _year <<"-"<< _month <<"-"<< _day << endl;}
}
bool operator==(const Date& d){
return _year==d._year && _month==d._month && _day==d._day;
}
bool operator!=(const Date& d){
return !(operator==(d));
bool operator>(const Date& d){
if (_year > year)
return true;
else if (_year==year && _month > month)
return true;
else if (_year==year && _month==month && _day > day)
return true;
else
return false;
}
bool operator>=(const Date& d){
return (operator>(d) || opreator==(d));
}
bool operator<(const Date& d){
return !(operator>=(d));
}
bool operator<=(const Date& d){
return !(operator>(d));
}
- += 和 -= ,变量本身改变,有返回值;+ 和 - ,变量本身不变 ,结果改变。
Date& operator+=(int days){
_day += days;
while(_day > GetMonthDay(_year,_month)){
if (month==12){
_day -= GetMonthDay(_year,_month);
_month = 1;
++_year;
}
else{
_day -= GetMonthDay(_year,_month);
++_month;
}
}
return *this;
}
Date& operator-=(int days){
_day -= days;
while(_day<=0){
if(_month==1){
_month = 12;
--_year;
_day += GetMonthDay(_year,_month);
}
else{
--_month;
_day += GetMonthDay(_year,_month);
}
}
return *this;
}
Date operator-(int days){
Date ret (*this);
ret -= 1;
return ret;
}
Date operator-(int days){
Date ret (*this);
ret += 1;
return ret;
}
int main ( ){
Date d1(2019,1,12);
d1 += 35;
d1.Print( );
d1 -=35;
d1.Print( );
printf ("%d-%d-%d\n",d1-35);
printf ("%d-%d-%d\n",d1+35);
}
- 前置++(- -)和后置++(- -)
//++d
Date& operator++(){
(*this) += 1;
return (*this);
}
Date& operator--(){
(*this) -= 1;
return (*this);
}
Date operator++(int){
Date ret = (*this);
(*this) += 1;
return ret;
}
Date operator++(int){
Date ret = (*this);
(*this) -= 1;
return ret;
}
- 两个日期相减
int operator-(const Date& d){
int ret = 0;
int flag = 1;
Date max = *this;
Date min = d;
if (*this < d){
max = d;
min = *this;
flag = -1;
}
while (min!=max){
min++;
ret++;
}
return ret*flag;
}
int main ( ){
Date d1(2019,12,3);
Date d2(2018,3,23);
cout << (d1-d2) << endl;
return 0;
}