在不需要变量i原数值的情况下,i++和++i哪个更好
学习笔记:
c++示例,告诉你++i的好处,平时也没太多时间搞原理。
不同编译器运行结果或有差异。
#include <iostream>
using namespace std;
class Number
{
public:
Number();
~Number();
Number(const Number&n);
Number& operator=(const Number&n);
Number& operator++();
Number operator++(int);
};
Number::Number()
{
}
Number::~Number()
{
cout<<"dtor ";
}
Number::Number(const Number&n) //产生Number的两个备份
{
cout<<"copy ";
}
Number&Number::operator=(const Number&n)
{
cout<<"assign ";return *this;
}
Number&Number::operator++()
{
cout<<"increament ";return *this;
}
Number Number::operator++(int)
{
Number old=*this;
++(*this);
return old; //返回局部变量old
}
int main()
{
Number n;
cout<<"++n:";++n;cout<<"\n";//输出++n的相关信息
cout<<"n++:";n++;cout<<"\n";//输出n++的相关信息
return 0;
}
该程序在后缀增量中产生Number的两个备份。最后的输出行是main()函数中n的释放,编译并运行程序,结果如下
对于内置类型,如int类型,优化程序能释放额外的备份。但对于用户定义的类类型,编译器则需要保持额外的构造函数和析构函数。
致谢范老师。