前言:
再来说一说函数运算
运算符重载函数是用来体现运算符的多态性,在学习C语言的过程中,运算符全都是用来解决内置类型数据、逻辑、关系表达式间的运算,而在学习C++的过程中,我们了解了类与对象,就会思考到自定义类型的对象之间是否也能进行+-*/等多种运算呢?基于此种想法,C++官方研发出了运算符重载函数,就是为了让自定义类型也能做运算,体现出了语言的多态性。
目录
前言:
一.前后置++运算重载
代码视图:
class Date
{
public:
Date(int year = 1900, int month = 1, int day = 1)
{
_year = year;
_month = month;
_day = day;
}
void Print() {
cout << _year << "-" << _month << "-" << _day << endl;
}
//获取月份天数
int GetMonthDay(int year, int month) {
int MonthDay[13] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 };
if ((month == 2) && ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))) {
return 29;
}
return MonthDay[month];
}
//+=运算符函数重载
Date& operator+=(int day) {
_day += day;
while (_day > GetMonthDay(_year, _month)) {
_day -= GetMonthDay(_year, _month);
_month++;
if (_month == 13) {
_year++;
_month = 1;
}
} return *this;
}
//前置++运算重载
Date& operator++() {
*this+=1;
return *this;
}
//后置为了和前置区分,在后置上约定加个int
Date operator++(int) {
Date tmp(*this); //调用拷贝构造
*this += 1;
return tmp; //返回临时对象,也要调用拷贝构造
}
private:
int _year;
int _month;
int _day;
};
int main() {
Date d1(2022, 2, 2);
Date d2(d1);
cout << "d1的日期前置结果:" << endl;
(++d1).Print(); //前置++
d1.Print();
cout << "d2的日期后置结果:" << endl;
(d2++).Print();
d2.Print();
return 0;
}
注意事项:
使用++运算符重载,需要用到+=的运算重载。
前置++中,this指针出了作用域已经不在了,但*this(d1)是整个main函数生命周期,仍在,所以用引用返回;而后置++中,tmp是临时拷贝对象,出了作用域不在了,不可用引用返回。
最后就是C++官方为了区分前置++与后置++的不同,专门为后置++的重载形参处多加了个int,这是约定好的,就好比双方谈好了,已经签了合同了,就不能再改了,所以大家不要以为能够换个char、double、short,这些写法都不对!!!
函数调用图示如下: