概述
我们在实现类的运算符重载时,只会去实现有意义的运算符重载,在日期Date类中,乘除等操作 没有用处,我们不用实现
class Date { public: int GetMonthDay(int year, int month)// 获取某年某月的天数 { static int arr[13] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 };//static 防止每次都要新建数组 if (month == 2 && year % 4 == 0 && year % 100 != 0 && year % 400 == 0) { return 29; } return arr[month]; } Date(int year = 1900, int month = 1, int day = 1) { _year = year; _month = month; _day = day; if (year <= 0 || month <= 0 || month >= 13 || day <= 0 || day > GetMonthDay(year, month)) { cout << _year << "/" << _month << "/" << _day <<"illegal date" << endl; } } void Print() const { cout << _year << "/" << _month << "/" << _day << endl; } Date& operator=(const Date& d); Date& operator+=(int day);// 日期+=天数 Date operator+(int day);// 日期+天数 Date operator-(int day);// 日期-天数 Date& operator-=(int day);// 日期-=天数 Date& operator++();// 前置++ Date operator++(int);// 后置++ Date operator--(int);// 后置-- Date& operator--();// 前置-- bool operator>(const Date& d);// >运算符重载 bool operator==(const Date& d);// ==运算符重载 inline bool operator >= (const Date& d);// >=运算符重载 bool operator < (const Date& d);// <运算符重载 bool operator <= (const Date& d);// <=运算符重载 bool operator != (const Date& d);// !=运算符重载 int operator-(const Date& d); // 日期-日期 返回天数 private: int _year; int _month; int _day; };
加等(+=)
思路
:
进位加法,注意day和month的限制,和month的置1Date& Date::operator+=(int day) { _day += day; while (_day>GetMonthDay(_year,_month)) { _day -= GetMonthDay(_year, _month); _month++; if (_month == 13) { _year++; _month = 1; } } return *this; }
加(+)
需要一个tmp类拷贝构造*this类,同时tmp复用‘
+=
’运算符Date Date::operator+(int day) { Date tmp(*this); tmp += day; return tmp; }
减等(-=)
思路
:
- 当day为负,复用“+=”
- 当为正数,用_day减去day,再循环加每个月的天数并判断直到正数,注意当month减为0的时候是跳为12
Date& Date::operator-=(int day) { if (day < 0) { return *this += -day; } _day -= day; while (_day <= 0) { --_month; if (_month == 0) { --_year; _month = 12; } _day += GetMonthDay(_year, _month); } return *this; }
减(-)
同理复用“
-=
”Date Date::operator-(int day) { Date ret(*this); ret -= day; return ret; }
前置++(- -)
d1++
同d1.operator++(&d1, 0)
按正常运算符重载规则,无法区分前置++和后置++,为了区分,这里就做一个特殊处理,给后置++增加一下int参数
,这个参数仅仅是为了区分
,这样他们俩就构成函数重载
前置++
Date& Date::operator++() { *this += 1; return *this; }
前置- -
Date& Date::operator--() { *this -= 1; return *this; }
后置++(- -)
后置++
Date Date::operator++(int) { Date tmp(*this); *this += 1; return tmp; }
后置- -
Date Date::operator--(int) { Date tmp(*this); *this -= 1; return *this; }
日期间相减(d1-d2)
小的向大的靠拢,每次复用‘++’,flag用于记录正负情况
int Date::operator-(const Date& d) { Date max = *this, min = d; int flag = 1; if (*this < d) { max = d; min = *this; flag = -1; } int n = 0; while (min != max) { ++min; ++n; } return n * flag; }
其他(==,!=,<=,>=,<,>…)
略。。