前置++和后置++重载

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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值