主要区别有三个
1、返回值不同
i++ 为后置加加,先返回i的值在对i进行自加一
++i 为前置加加,先自加一再返回i的值
2、在类中的重载方式不同
前置加加可以用类类型对象的引用来接收返回值,并且没有参数,给this加一后即可返回*this
后置加加不能使用引用,为了与前置++构成重载,需要给出一个参数int,内部先用*this拷贝构造一份临时temp,自加一后返回临时temp
class001& operator++()
{
*this+=1;
return *this;
}
const class001 operator++(int)
{
class001 temp(*this);
*this+=1;
return temp;
}
#pragma once
#include<iostream>
using namespace std;
class class001
{
public:
class001 (int i = 0)
: _i(i)
{}
class001(const class001& j)
: _i(j._i)
{}
class001& operator++()
{
_i++;
return *this;
}
const class001 operator++(int)
{
class001 temp(*this);
_i++;
return temp;
}
private:
int _i;
};
// ++i 与 i++
void Test001()
{
class001 s001(10);
++s001;
s001++;
}
3、i++不能成为左值,而++i可以
左值与右值的本质区别在于是否能放在 赋值表达式(=)的左侧
左值(L_value)(存储在计算机内存的对象,可寻址!!!)
右值(R_value)(一个数据值)
i++ 返回的是一个临时变量,它是一个数据
++i接收到的是一个变量i 可以对这个变量i取地址
++i = 1 --> i = 1; i++ = 1 错误