习题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*());
}