C++重载运算符3--自增运算符
# 一、自增运算符重载 自增运算符重载分为两种a++与++a,a++是先输出,然后在自增,++a是先自增,然后在输出。
1.成员函数重载
#include<iostream>
#include<string>
using namespace std;
class Person
{
publiuc:
Person()
{
m_age=10;
}
Person& operator++()//++a
{
m_age++;
return *this;
}
Person operator++(int)
{
Person temp;
temp=*this;
m_age++;
return temp;//因为这边temp是一个局部变量,运行完就被释放,所以这里只能返回值,不能返回引用
}
private:
int m_age;
};
void test()
{
Person p;
p++;
++p;
}
int main()
{
test();
return 0;
}