c++是部分面向对象的语言,在对待自定义类型时是以面向对象方式处理,对待内置类型时它是按照面向过程的方式处理。
在c++中,对于内置类型变量的自增自减规律:前置++/--,先+/-再使用。后置++/--,先使用(什么时候使用完了;,?),再+/-。
例如如下代码:
int main()
{
int i = 0;
i = i++ +1;
cout<<"i = "<<i<<endl;
}
输出结果为 i = 2;
其中 i = i++ +1 ; 语句的汇编指令为:
00D27FA5 mov eax,dword ptr [i]
00D27FA8 add eax,1
00D27FAB mov dword ptr [i],eax
00D27FAE mov ecx,dword ptr [i]
00D27FB1 add ecx,1
00D27FB4 mov dword ptr [i],ecx
在c++中,对于自定义类型的自增自减:无论是前置还是后置的++/--,都是调用的类里面的成员函数,得到的结果是成员函数的返回值。
例如如下代码:
class Int
{
private:
int value;
public:
Int(int x=0):value(x) {}
Int(const Int &it):value(it.value) {}
Int & operator=(const Int &it)
{
if(this != &it)
{
value = it.value;
}
return *this;
}
Int & operator++()
{
value +=1;
return *this;
}
Int operator++(int)
{
return value++;
}
Int operator+(const Int &it) const
{
return Int(this->value+it.value);
}
friend ostream & operator<<(ostream &out,const Int &it);
};
ostream & operator<<(ostream &out,const Int &it)
{
out<<it.value;
return out;
}
int main()
{
Int a = 0;
a = a++ +1;
cout<<"a = "<<a<<endl;
return 0;
}
输出结果为 a = 1; 其中的a++实质上是调用的类里面的成员函数,a.operator++(int);
看下面代码的输出结果,再次理解一下前置后置++的区别:
int main()
{
int a = 10;
cout<<(++a)+(++a)+(++a)<<endl; // 39
cout<<a<<endl;//13
return 0;
}
输出结果为 39 13
int main()
{
int a = 10;
cout<<(a++)+(a++)+(a++)<<endl;//30
cout<<a<<endl;//13
return 0;
}
输出结果为 30 13