《More Effective C++》6:区别递加和递减符号的前置和后置形式

C++允许对自增符号“++”,和自减符号”--“进行重载,但众所周知,前置的”++“、”--“和后置的意义是不一样的,

而且更糟糕的是,他们的前置式和后置式都是没有参数的,这就让我们的重载变得不可能了。

为了填补这个语言学上的漏洞,C++让后置式有一个int型的参数,并在它被调用的时候,

编译器自动为该int指定一个0值。 ex:

#include <iostream>

using namespace std;

//记录整百的数
class Hundreds
{
public:
	Hundreds(int org = 0) { data = org - (org % 100); }

	Hundreds& operator++(); // 前置(prefix)的 “++”
	const Hundreds operator++(int); //后置(postfix)的 “++”

	Hundreds& operator--(); //前置的 “--”
	const Hundreds operator--(int); //后置的“--”

	void Show() const { cout << data << endl; }
private:
	int data;
};

Hundreds& Hundreds::operator++()
{
	data += 100;
	return *this;
}
const Hundreds Hundreds::operator++(int)
{
	Hundreds oldValue = *this; //记录旧数据
	data += 100;
	return oldValue;
}

Hundreds& Hundreds::operator--()
{
	data -= 100;
	return *this;
}
const Hundreds Hundreds::operator--(int)
{
	Hundreds oldValue = *this;
	data -= 100;
	return oldValue;
}

int main()
{
	Hundreds hd(100);
	
	//测试“++”操作符

	//取出后累加:fetch and increment.
	(hd++).Show();  //显示100,等价于(hd.operator++(0)).Show();
	hd.Show();      //显示200
	//累加后取出:increment and fetch.
	(++hd).Show();   //显示300,等价于(hd.operator++()).Show();
	hd.Show();       //显示300
	
	//“--”操作符与之类似
	//... ...

	return 0;
}
效果如图:

为什么后置式的返回值要是const的对象呢? 

因为后置式的返回值不再是现在的变量,而是旧值,因此,类似hd++++的式子应该是不合法的。因为,

如果hd++++是合法的,则,第一个“++”的返回值就不是hd,因此,后一个"++"并不是作用于hd的函数,

让人产生混淆,所以,我们还是废了这种想法吧。所以我们让它返回const对象。

(PS:然而前置式如++++hd则是合法的,因为它的返回值正是hd的引用。)


有了上面的分析,我们就能够理解为什么在前置式和后置式都可选的情况下,我们应该尽量选用前置式。

毕竟前置式没有“oldValue”这个中间变量的羁绊。毕竟这个中间变量也是需要构造和析构的嘛。






  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值