《C++ Primer》第14章 14.6节习题答案

《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的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值