第十四章 习题14-21-习题14-30

习题14-21

Sales_data& Sales_data::operator+=(const Sales_data &rhs)
{
    Sales_data temp = *this;
    *this = temp + rhs;
    return *this;
}

Sales_data& operator+ (const Sales_data& lhs, const Sales_data& rhs)
{
	Sales_data ret(lhs);
	lhs.units_sold += rhs.units_sold;
	lhs.revenue += rhs.revenue;
	return ret;
}

习题14-22 

Sales_data& Sales_data::operator=(const string& isbn)
{
    *this = Sales_data(isbn);
    return *this;
}

习题14-23

StrVec& StrVec::operator=(initializer_list<std::string> il)
{
    auto data = alloc_n_copy(il.begin(), il.end());
    free();
    elements = data.first;
    first_free = cap = data.second;
    return *this;
}

 习题14-24

习题14-25

习题14-26

// String类
char String::operator[] (size_t n)
{
    if (n < 0 || n > size()) 
    {
        cout << "out of range." << endl;
        return 0;
    }
    return begin[n];
}

const char String::operator[] (size_t n) const
{
    if (n < 0 || n > size()) {
        cout << "out of range." << endl;
        return 0;
    }
    return begin[n];
}

// StrVec类
std::string& operator[] (size_t n) 
{ 
    return elements[n]; 
}
const std::string& operator[] (size_t n) const 
{ 
    return elements[n]; 
}

习题14-27

StrBlobPtr& operator++ ()
{
    check(curr, "increment past end of StrBlobPtr");
    ++ curr;
    return *this;
}

StrBlobPtr& operator-- ()
{
    -- curr;
    check(curr, "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& StrBlobPtr::operator+=(size_t n)
{
    curr += n;
    check(curr, "increment past end of StrBlobPtr");
    return *this;
}

StrBlobPtr& StrBlobPtr::operator-=(size_t n)
{
    curr -= n;
    check(curr, "increment past end of StrBlobPtr");
    return *this;
}

 StrBlobPtr StrBlobPtr::operator+(size_t n) const
{
    StrBlobPtr ret = *this;
    ret += n;
    return ret;
}

StrBlobPtr StrBlobPtr::operator-(size_t n) const
{
    StrBlobPtr ret = *this;
    ret -= n;
    return ret;
}

习题14-29

因为递增和递减运算改变了对象,不能用const对象;

习题14-30

string& operator* () const
{
    auto p = check(curr, "dereference past end");
    return (*p)[curr];
}

string* operator->() const
{
    return &(this->operator*());
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值