classBigInt
{
public:
BigInt & operator++(); // ++ BigInt
BigInt operator++(int unused); // BigInt ++
//..
};
这两个不同的操作符的执行说明了它们在性能上的区别:
BigInt & BigInt::operator++() //
++ BigInt is preferable
{
AddDays(1); //increment current
object
return *this; //return by reference the
current object
}
BigIntBigInt::operator++(int unused) // BigInt ++; less
efficient
{
BigInttemp(*this); //copy of the current
object
AddDays(1); //increment current object
return temp; //return copy
}
虽然这些执行可以进一步的改进(例如,使用+=),但后缀操作符效率要低得多。除了调用一个成员函数,它还需要建立一个当前对象,并返回它的值。而对于前缀操作符,它需要调用一个成员函数和返回一个引用。为了对这两种操作符进行性能评价,可以使用后缀操作符运行,再用前缀操作符替换后缀操作符运行,然后检测这两个过程的时间。
对于前缀和后缀操作符的选择,这里有一个规律:当在相同赋值情况下选择后缀和前缀操作符,你应该选择前缀操作符。