【C++】日期类的实现
目录
比较运算符重载
关于 < 重载的判断逻辑
相对简洁的比较逻辑
//注意这里分情况讨论的逻辑
bool Date::operator<(const Date& d) const
{if (_year == d._year && _month == d._month){return _day < d._day;}else{if (_year == d._year){return _month < d._month;}else{return _year < d._year;}}
}
- 实现时注意使用以实现的运算符重载**
- 在不改变自身对象成员的情况下,最好加上const**
bool operator==(const Date& d) const;bool operator!=(const Date& d) const;bool operator<(const Date& d) const;bool operator<=(const Date& d) const;bool operator>(const Date& d) const;bool operator>=(const Date& d) const;
算数运算符重载
关于复用+还是复用+=
- 在+中复用+=,则使用+时需拷贝构造,而+=时不用
- 若在+=中复用+,则使用+和+=时都需拷贝构造
- 所以最好在+中复用+=,以减少调用拷贝构造
//在+中复用+=,则使用+时需拷贝构造,而+=时不用
//若在+=中复用+,则使用+和+=时都需拷贝构造
//所以最好在+中复用+=,以减少调用拷贝构造
Date Date::operator+(int day) const
{/*Date tmp(*this);tmp._day += day;while (tmp._day > tmp.GetMonthDay()){tmp._day -= tmp.GetMonthDay();++tmp._month;if (tmp._month == 13){++tmp._year;tmp._month = 1;}}return tmp;*/Date tmp(*this);tmp += day;return tmp;
}Date& Date::operator+=(int day)
{_day += day;while (_day > GetMonthDay()){_day -= GetMonthDay();++_month;if (_month == 13){++_year;_month = 1;}}//*this = *this + day;return *this;
}
关于两个日期对象相减
- 设定大对象和小对象,同时设置flag
- 若预设不对,则交换,flag变-1
- 返回日期差 * flag
//Date 减 Date
int Date::operator-(Date& d) const
{int ret = 0;int flag = 1;Date max = *this;Date min = d;if (max < min){max = d;min = *this;flag = -1;}while (min < max){min = min + 1;++ret;}return flag * ret;
}
注意考虑天数的正负
当+重载中的天数为负时,增加判断条件,其他同理
Date tmp(*this);if (day < 0){tmp -= (-day);}else{tmp += day;}return tmp;
//获取当月天数int GetMonthDay() const;//日期加减天数Date operator+(int day) const;Date& operator+=(int day);Date operator-(int day) const;Date& operator-=(int day);//Date 减 Dateint operator-(Date& d) const;
前置++,后置++ 重载
关于前置++和后置++运算符重载的参数问题
Date& operator++();//++d2;Date operator++(int);//d2++;
- 前置++
因为是前置++,操作对象在++的后面,且只有一个类对象参数(隐含的参数,不显示),直接匹配 - 后置++
操作对象在++之前,先匹配到隐含参数,第二个占位参数编译器自动匹配,调用时不用主动传递,从而与前置++构成重载
关于++重载函数返回值:
++可能存在连续赋值,如 (d2++)++
,故需返回类对象(前置返回引用即可)
--
运算符重载同理
流运算符的重载
考虑到流运算符的操作数的左右顺序,以及成员函数默认第一个隐含参数为自身对象
所以实现流运算符重载时需要借助友元函数实现,从而实现参数顺序同操作数顺序匹配