(++a)+=(a++)跟(++a)=(++a)+(a++)的区别

(++a)+=(a++)和(++a)=(++a)+(a++)的区别
#include <iostream>
using namespace std;
void main()
{
  int a=4;
  cout<<((++a)+=(a++))<<endl;   //结果为10
  cout<<a<<endl;              //结果为11
  system("pause");
}
#include <iostream>
using namespace std;
void main()
{
  int a=4;
  cout<<((++a)=(++a)+(a++))<<endl;   //结果为12
  cout<<a<<endl;              //结果为13
  system("pause");
}

两者结果不一致,为什么呢?

首先先说说为什么(i++)不能做左值而(++i)可以。

//前缀形式,如++a
int &int::operator++()
{
   *this+=1;
   return *this;
}

//后缀形式,如a++,由于返回的是副本,所以设定了const int,因为给oldvalue赋值是危险的,函数出栈动作结束后,oldvalue就消失了。
const int int::operator++(int)
{
   int oldvalue=*this;
   ++(*this);
   return oldvalue;
}
那么(++a)+=(a++)和(++a)=(++a)+(a++)的结果为什么不同呢?

首先,10和11,12和13的不同时由于a++造成的。

(++a)+=(a++)

其实是先++a,那么a变成5,(a++)之后返回副本值还是5,那么5+5为10。