前置++和后置++的区别

#include<iostream>
using namespace std;

class Int
{
	friend ostream& operator<<(ostream& os,const Int& i);
public:
	Int(int i) :m_i(i){}
	~Int();
	/*const Int operator++(int)
	{
		Int tmp = *this;
		(this->m_i)++;
		return tmp;
	}*/
	Int & operator++()
	{
		(this->m_i)++;
		return *this;
	}

private:
	int m_i;
};

ostream& operator<<(ostream& os, const Int& i)
{
	os <<i.m_i<<'\t'<< endl;
	return os;
}

int main()
{
	Int a(10);
	Int b(15);
	++a;
	//a++;
	cout << a;
	return 0;
}

重载操作符++,前置++和后置++的区别的,前置的代码是
Int & operator++()
{
(this->m_i)++;
return *this;
}
可以使用++a而此时不能使用a++,后置代码是
const Int operator++(int)
{
Int tmp = *this;
(this->m_i)++;
return tmp;
}
此时则可以使用a++,自定义类时必须要区分。带参数时则是后置,无参数时则是前置仅仅用于区分,无实际意义。因此在使用时最好使用前置++,无多余的临时变量产生。前置返回引用可以加快运行速率。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值