C++ Primer 5th notes (chap 14 overload operation and type conversion) increment and decrement operators

  • It is not required that the increment and decrement operators must be member functions of the class, but because this operator changes the state of the object being operated on, it is recommended to set them as member functions.

  • In order to be consistent with the built-in version, the preceding operator should return the reference of the object after incrementing or decrementing.

  • In order to be consistent with the built-in version, the post operator should return the value of the object before the increment or decrement, not a reference.

  • Increment and decrement operators should define both the pre and post versions at the same time.

  • The normal overloaded form cannot distinguish between pre-operation and post-operation. In order to solve this problem, the post-version version adds an extra unused int type parameter:

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;
};

If you want to use post-increment or decrement operators by way of function calls, you must pass a value for its integer parameter and call it explicitly.

StrBlobPtr p(a);
p.operator++(0);	//后置版本
p.operator++();		//前置版本

Guess you like

Origin blog.csdn.net/thefist11cc/article/details/113928259