[置顶] 【C/C++学习】之十二、++i与i++的区别

大家都应该知道i++和++i的区别,前者是先使用i的值,然后再增加1,而后者是先增加1然后再使用i的值。

但是i++和++i那个更好呢? 我们通过程序来比较一下:

#include<iostream>
using namespace std;

class I{
public:
	I();
	~I();

	I(const I &i);
	I& operator=(const I &i);
	I& operator++();
	I operator++(int);
};

I::I()
{
	cout << "con" << endl;
}

I::~I()
{
	cout << "dector" << endl;
}

I::I(const I& i)
{
	cout << "copy" << endl;
}

I& I::operator++()
{
	cout << "increament" << endl;
	return *this;
}

I& I::operator=(const I &i)
{
	cout << "assign" << endl;
	return *this;
}

I I::operator++(int)
{
	I old = *this;
	++(*this);
	return old;
}

int main(void)
{
	I i;
	cout << "++i" << endl;
	++i;
	cout << endl;
	cout << "i++" << endl;
	i++;
	cout << endl;

	return 0;
}



结果是:



从执行结果可以看出,++i就调用了一次构造函数,一次++操作,

而i++ 调用了两次复制构造函数,两次析构函数,一次++操作符。

通过上述的比较,大家可以看出是那个效率更好了吧!!!


2012/9/29

jofranks 于南昌

原文地址:https://www.cnblogs.com/java20130723/p/3211397.html