-
并不要求递增和递减运算符一定是类的成员函数,但是因为这个运算符改变的正好是所操作的对象的状态,所以建议将它们设为成员函数。
-
为了和内置版本保持一致,前置运算符应该返回递增或递减后对象的引用。
-
为了和内置版本保持一致,后置运算符应该返回递增或递减前对象的值,而不是引用。
-
递增和递减运算符应该同时定义前置和后置两个版本。
-
普通的重载形式无法区分是前置运算还是后置运算,为了解决这个问题,后置版本加上一个额外的不被使用的 int 类型参数:
class StrBlobPtr
{
public:
// increment and decrement
//前置版本
StrBlobPtr& operator++(); // prefix operators
StrBlobPtr& operator--();
//后置版本
StrBlobPtr operator++(int); // postfix operators
StrBlobPtr operator--(int);
};
StrBlobPtr & StrBlobPt::operator++()
{
check(curr,"increment past end of StrBlobPtr");
++cur;
return *this;
}
StrBlobPtr & StrBlobPt::operator--()
{
--cur;
check(curr,"increment past end of StrBlobPtr");
return *this;
};
//后置版本调用前置版本来完成
StrBlobPtr & StrBlobPt::operator++(int)
{
StrBlobPt ret = *this;
++*this;
return ret;
}
//后置版本调用前置版本来完成
StrBlobPtr & StrBlobPt::operator--(int)
{
StrBlobPt ret = *this;
--*this;
return ret;
};
如果想通过函数调用的方式使用后置递增或递减运算符,则必须为它的整型参数传递一个值显式调用。
StrBlobPtr p(a);
p.operator++(0); //后置版本
p.operator++(); //前置版本