目录
单目递增运算符的重载
单目递增运算符重载简介
弹幕递增运算符重载(++)可分为前缀和后缀两种,即++I,i++两种。为此我们也将重载分为两类,前缀单目递增运算符重载与后缀弹幕递增运算符重载。
系统默认++i这种类型的重载是正常情况下的重载,而i++这种类型的重载则被视为特殊情况下的单目运算符重载,需要加后缀运算标志。
++做前缀
++做前缀的代码示例
#include <iostream>
#include <string>
using namespace std;
class Data
{
private:
int Day;
int Month;
int Year;
public:
Data(int Day, int Month, int Year)
{
this->Day = Day;
this->Month = Month;
this->Year = Year;
}
~Data()
{
cout << "调用Data的析构函数" << endl;
}
void ShowInf()
{
cout << "今天为:" << this->Year << "年" << this->Month << "月" << this->Day << "日" << endl;
}
// 前缀单目递增运算符
Data& operator++ () // 无需参数,因为已经传入默认参数this指针
{
if ((this->Day > 32) || (this->Month > 12))
{
return *this;
}
else
{
if ((this->Day) == 32)
{
this->Day = 1;
if ((this->Month) == 12)
{
this->Month = 1;
this->Year++;
}
}
else
{
this->Day++;
}
}
return *this; // 返回Data类的对象
}
};
int main()
{
Data data(12, 7, 2020);
++data;
data.ShowInf();
}
递增运算符函数体内部流程
我们都知道++i应该先执行i=i+1的自加1运算,在执行i的赋值运算,….等其他运算。我们重载运算符也一定要按照这样的规范,重载运算符是扩充功能并不是颠覆规则。因此,我们先对Data的对象进行+1运算,在进行输出return。
++做后缀
++做后缀的代码示例
#include <iostream>
using namespace std;
class Data
{
private:
int Year;
int Month;
int Day;
public:
Data(int Year, int Month, int Day)
{
this->Year = Year;
this->Month = Month;
this->Day = Day;
}
~Data()
{
cout << "调用Data的析构函数" << endl;
}
Data& operator++ (int) // int为后缀单目运算符重载的关键字
{
Data *data = new Data(Year, Month, Day);
if ((this->Day > 32) || (this->Month > 12))
{
return *this;
}
else
{
if ((this->Day) == 32)
{
this->Day = 1;
if ((this->Month) == 12)
{
this->Month = 1;
this->Year++;
}
}
else
{
this->Day++;
}
}
return *data;
}
void ShowInf()
{
cout << "今天为:" << this->Year << "年" << this->Month << "月" << this->Day << "日" << endl;
}
};
int main()
{
Data data(2020, 7, 12), data1 = data++; // data自加1,然后进行值拷贝给data1
data.ShowInf(); // 2020.7.13
data1.ShowInf(); // 2020.7.12
}
代码解析
这个operator++的函数定义中采用了先return对象后进行自加1的操作,这样操作符合i++的操作流程:先进行其他运算(例如:赋值….)然后再进行自加1运算。如果单独使用前缀++和后缀++,其实效果一样,为什么呢?
因为这是return返回值无人接收,而且再函数体内部都进行了自加1的运算,因此最后调用时,Data对象data自身都加了1。
切记:后缀++重载一定要在operator++函数形参中加int关键字!