🌈个人主页:羽晨同学
💫个人格言:“成为自己未来的主人~”
前置++和后置++重载
首先,我们先来看到二者实现的代码:
#include<iostream>
using namespace std;
class Date
{
public:
Date(int year = 2024, int month = 5, int day = 17)
{
_year = year;
_month = month;
_day = day;
}
//前置++
Date& operator++()
{
_day += 1;
return *this;
}
//后置++
Date operator++(int)
{
Date tmp(*this);
_day += 1;
return tmp;
}
void Print()
{
cout << _year << "-" << _month << "-" << _day << endl;
}
private:
int _year;
int _month;
int _day;
};
int main()
{
Date d1(2024, 1, 1);
Date d2(2024, 1, 1);
Date d3=d1++;
Date d4=++d2;
d3.Print();
d4.Print();
return 0;
}
这个代码的实现逻辑是什么呢?
让我们一个个来进行分析,
//前置++
Date& operator++()
{
_day += 1;
return *this;
}
//后置++
Date operator++(int)
{
Date tmp(*this);
_day += 1;
return tmp;
}
由于系统默认生成的*this指针不会进行销毁,所以,我们直接选择传*this指针,设为引用类型,这样子可以提高效率,而对于后置++而言,我们需要先使用,再+1,所以,我们需要先设定一个新的变量用来接收此时的*this的值,然后再对其进行修改。
在C++11当中,为了进一步的进行区分,我们将后置++当中的参数设置为int类型 ,用来进行区分。
好了,这个就是运算符重载当中的前置++和后置++的重载过程,下一节,我们将会带大家走进日期类的实现。