对于int类型变量a可以如下操作
++a;
a++;
--a;
a--;
++和--分别都有前置式(操作符在前)、后置式(操作符在后)
对于自定义类型,++和--的重载需要区分前置式和后置式,如下
class Element
{
public:
Element(int value) :value_(value) {}
Element& operator++()
{
++value_;
return *this;
}
const Element operator++(int)
{
Element cache = *this;
++value_;
return cache;
}
Element& operator--()
{
--value_;
return *this;
}
const Element operator--(int)
{
Element cache = *this;
--value_;
return cache;
}
private:
int value_;
};
Element a(0);
auto b = a++; // b.value_ = 0; a.value_ = 1
auto c = ++++a; // c.value_ = 3; a.value_ = 3
auto d = a++++; // compile error
前置式返回的是引用&,是左值;
后置式返回的是常量对象,是右值,同时带有一个不使用的int参数。
本文详细讲解了如何为自定义类Element实现前置和后置++和--操作符重载,强调了返回值类型的区别,并通过实例演示了前置式和后置式的使用。
7857

被折叠的 条评论
为什么被折叠?



