《C++ Primer》第14章 操作重载与类型转换
14.6节 递增和递减运算符 习题答案
练习14.27:为你的StrBlobPtr类添加递增和递减运算符。
【出题思路】
本题练习实现递增和递减运算符。
【解答】
class StrBlobPtr
{
public:
//前缀
StrBlobPtr& operator++();
StrBlobPtr& operator--();
//后缀
StrBlobPtr operator++(int);
StrBlobPtr operator--(int);
};
StrBlobPtr& StrBlobPtr::operator++()
{
check(curr, " increment past end of StrBlobPtr");
++curr;
return *this;
}
StrBlobPtr& StrBlobPtr::operator--()
{
--curr;
check(-1, " decrement past begin of StrBlobPtr");
return *this;
}
StrBlobPtr StrBlobPtr::operator++(int)
{
StrBlobPtr ret = *this;
++(*this);
return ret;
}
StrBlobPtr StrBlobPtr::operator--(int)
{
StrBlobPtr ret = *this;
--(*this);
return ret;
}
练习14.28:为你的StrBlobPtr类添加加法和减法运算符,使其可以实现指针的算术运算(参见3.5.3节,第106页)。
【出题思路】
本题练习实现加法和减法运算符。
【解答】
class StrBlobPtr
{
friend StrBlobPtr operator+(int n);
friend StrBlobPtr operator-(int n);
//其他成员
private:
int curr;
};
StrBlobPtr StrBlobPtr::operator+(int n)
{
auto ret = *this;
ret.curr += n;
return ret;
}
StrBlobPtr StrBlobPtr::operator-(int n)
{
auto ret = *this;
ret.curr -= n;
return ret;
}
练习14.29:为什么不定义const版本的递增和递减运算符?
【出题思路】
理解递增和递减运算符。
【解答】
对于++和--运算符,无论它是前缀版本还是后缀版本,都会改变对象本身的值,因此不能定义成const的。