1、前置++重载时没有参数,而后置++重载时有参数。不会使用其参数,仅仅是区分用。可以理解为前置++后面有参数了,所以不需要参数
++i 对应 operator++()
i++ 对应 operator++(int)
2、前置++需要返回引用,因为重载自加运算符后可以返回对象的引用, 以方便在表达式中连续使用。而后置++返回的不是引用,所以不能进行连续使用。
#include<iostream>
#include<vector>
using namespace std;
class node
{
public:
node(int a, int b) :x(a), y(b){}
node(){ x = 1; y = 1; }
node &operator++() //前置++,++i
{
x++;
y++;
return *this;
}
node operator++(int) //后置++,i++
{
node temp = *this; //保存变量初始值,用于返回
x++;
y++;
return temp;
}
void print()
{
cout << "x: " << x << " " << "y: " << y << endl;
}
private:
int x;
int y;
};
int main()
{
node a;
a.print();
node b=++a;
a.print();
b.print();
node c = a++;
a.print();
c.print();
system("pause");
return 0;
}