下面是一个简单的例子模拟分析++源码:
class CInt {
private :
int m_value;
} ;
CInt & CInt:: operator ++ ( ) // 前置的是没有参数的,并且返回引用
{
this -> m_value += 1 ;
return * this ;
}
const CInt CInt::opeartor ++ (Int) // 后置的有一个匿名参数,并且返回const值
{
Const old = * this ;
++ ( * this );
return old;
}
前置仅仅是对自身进行运算,并将自身返回,这样外面可以直接对这个返回对象再进行操作 ,如(++it)->function()。
后置因其返回的不是原来的对象,此时再进行额外操作,改变的是临时对象的状态。
‘++i’ is equivalent to: ‘i=i+1; /* then use ‘i’ as the ‘i’ in your expression. */’
‘i++’ is equivalent to: ‘int tmp = i; i=i+1; /* then use ‘tmp’ as ‘i’ in your expression. */’
so ‘++i’ is a bit more efficient than ‘i++’. however, if you just write a stand-along ‘i++’ or ‘++i’, the temporary object ‘tmp’ is unnecessary, so any compiler should be able to completely optimize that way, making ‘i++’ is equally efficient as ‘++i’.