前置++和后置++的区别及其重载
(2016-03-06 22:21:54)
标签:
前置后置 |
分类: c/c |
1:两者的区别:
实现原理是什么?
一个例子:
-
class
Age -
{
-
public:
-
-
Age& operator++() //前置++ -
{ -
++i; -
return * this; -
} -
-
const Age int)operator++( //后置++ -
{ -
Age tmp = *this; -
++(*this); -
return tmp; -
} -
-
Age& operator=(int i) //赋值操作 -
{ -
this->i = i; -
return * this; -
} -
-
private:
-
int i; -
};
返回值类型:++i返回的是引用,而i++返回的则是
const类型。其中const类型不能对他进行其他操作,二引用可以。
举个例子:
-
int
main() -
{
-
Age a; -
-
(a++)++; //编译错误 -
++(a++); //编译错误 -
a++ = 1; //编译错误 -
(++a)++; //OK -
++(++a); //OK -
++a = 1; //OK -
}
a++的类型是const XX ,自然不能对它进行前置++、后置++、赋值等操作。
++a的类型是XX &,当然可以对它进行前置++、后置++、赋值等操作2:如何进行重载呢?如何区别?
例如:
class A3:优先使用前置++
{
private:
int a;
public:
& operator++() A
{
+(int) ++a; return *this; //直接进行++并且返回其引用
//前置++ //...
}
operator+ A
{
后置++ //... A a = *this; ++*this; //先做一个副本
//对其本身进行++的操作
return a; //
}
}
-
const
Age int)operator++( //后置++ -
{
-
Age tmp = *this; -
++(*this); -
return tmp; -
}
前一篇:[转载]卵巢保健知多少
后一篇:关于如何求最大公约数