湘潭市 网站建设/seo兼职论坛
文章目录
- 练习14.21
- 练习14.22
- 头文件
- CPP文件
- 练习14.23
- 头文件
- CPP文件
- 练习14.24
- 头文件
- CPP文件
- 练习14.25
- 练习14.26
- 练习14.27
- 练习14.28
- 练习14.29
- 练习14.30
练习14.21
编写 Sales_data 类的+ 和+= 运算符,使得 + 执行实际的加法操作而 += 调用+。相比14.3节和14.4节对这两个运算符的定义,本题的定义有何缺点?试讨论之。
缺点:使用了一个 Sales_data
的临时对象,但它并不是必须的。
练习14.22
定义赋值运算符的一个新版本,使得我们能把一个表示 ISBN 的 string 赋给一个 Sales_data 对象。
头文件
#ifndef CP5_ex14_22_h
#define CP5_ex14_22_h#include <string>
#include <iostream>class Sales_data
{friend std::istream& operator>>(std::istream&, Sales_data&);friend std::ostream& operator<<(std::ostream&, const Sales_data&);friend Sales_data operator+(const Sales_data&, const Sales_data&);public:Sales_data(const std::string &s, unsigned n, double p) :bookNo(s), units_sold(n), revenue(n*p) {}Sales_data() : Sales_data("", 0, 0.0f) {}Sales_data(const std::string &s) : Sales_data(s, 0, 0.0f) {}Sales_data(std::istream &is);Sales_data& operator=(const std::string&);Sales_data& operator+=(const Sales_data&);std::string isbn() const { return bookNo; }private:inline double avg_price() const;std::string bookNo;unsigned units_sold = 0;double revenue = 0.0;
};std::istream& operator>>(std::istream&, Sales_data&);
std::ostream& operator<<(std::ostream&, const Sales_data&);
Sales_data operator+(const Sales_data&, const Sales_data&);inline double Sales_data::avg_price() const
{return units_sold ? revenue / units_sold : 0;
}#endif
CPP文件
#include "exercise14_22.h"Sales_data::Sales_data(std::istream &is) : Sales_data()
{is >> *this;
}Sales_data& Sales_data::operator+=(const Sales_data &rhs)
{units_sold += rhs.units_sold;revenue += rhs.revenue;return *this;
}std::istream& operator>>(std::istream &is, Sales_data &item)
{double price = 0.0;is >> item.bookNo >> item.units_sold >> price;if (is)item.revenue = price * item.units_sold;elseitem = Sales_data();return is;
}std::ostream& operator<<(std::ostream &os, const Sales_data &item)
{os << item.isbn() << " " << item.units_sold << " " << item.revenue << " " << item.avg_price();return os;
}Sales_data operator+(const Sales_data &lhs, const Sales_data &rhs)
{Sales_data sum = lhs;sum += rhs;return sum;
}Sales_data& Sales_data::operator=(const std::string &isbn)
{*this = Sales_data(isbn);return *this;
}
练习14.23
为你的StrVec 类定义一个 initializer_list 赋值运算符。
头文件
#ifndef CP5_STRVEC_H_
#define CP5_STRVEC_H_#include <memory>
#include <string>
#include <initializer_list>#ifndef _MSC_VER
#define NOEXCEPT noexcept
#else
#define NOEXCEPT
#endifclass StrVec
{friend bool operator==(const StrVec&, const StrVec&);friend bool operator!=(const StrVec&, const StrVec&);friend bool operator< (const StrVec&, const StrVec&);friend bool operator> (const StrVec&, const StrVec&);friend bool operator<=(const StrVec&, const StrVec&);friend bool operator>=(const StrVec&, const StrVec&);public:StrVec() : elements(nullptr), first_free(nullptr), cap(nullptr) {}StrVec(std::initializer_list<std::string>);StrVec(const StrVec&);StrVec& operator=(const StrVec&);StrVec(StrVec&&) NOEXCEPT;StrVec& operator=(StrVec&&)NOEXCEPT;~StrVec();StrVec& operator=(std::initializer_list<std::string>);void push_back(const std::string&);size_t size() const { return first_free - elements; }size_t capacity() const { return cap - elements; }std::string *begin() const { return elements; }std::string *end() const { return first_free; }std::string& at(size_t pos) { return *(elements + pos); }const std::string& at(size_t pos) const { return *(elements + pos); }void reserve(size_t new_cap);void resize(size_t count);void resize(size_t count, const std::string&);private:std::pair<std::string*, std::string*> alloc_n_copy(const std::string*, const std::string*);void free();void chk_n_alloc() { if (size() == capacity()) reallocate(); }void reallocate();void alloc_n_move(size_t new_cap);void range_initialize(const std::string*, const std::string*);private:std::string *elements;std::string *first_free;std::string *cap;std::allocator<std::string> alloc;
};bool operator==(const StrVec&, const StrVec&);
bool operator!=(const StrVec&, const StrVec&);
bool operator< (const StrVec&, const StrVec&);
bool operator> (const StrVec&, const StrVec&);
bool operator<=(const StrVec&, const StrVec&);
bool operator>=(const StrVec&, const StrVec&);#endif
CPP文件
#include "exercise14_23.h"
#include <algorithm>void StrVec::push_back(const std::string &s)
{chk_n_alloc();alloc.construct(first_free++, s);
}std::pair<std::string*, std::string*>
StrVec::alloc_n_copy(const std::string *b, const std::string *e)
{auto data = alloc.allocate(e - b);return{ data, std::uninitialized_copy(b, e, data) };
}void StrVec::free()
{if (elements){for_each(elements, first_free, [this](std::string &rhs) { alloc.destroy(&rhs); });alloc.deallocate(elements, cap - elements);}
}void StrVec::range_initialize(const std::string *first, const std::string *last)
{auto newdata = alloc_n_copy(first, last);elements = newdata.first;first_free = cap = newdata.second;
}StrVec::StrVec(const StrVec &rhs)
{range_initialize(rhs.begin(), rhs.end());
}StrVec::StrVec(std::initializer_list<std::string> il)
{range_initialize(il.begin(), il.end());
}StrVec::~StrVec()
{free();
}StrVec& StrVec::operator = (const StrVec &rhs)
{auto data = alloc_n_copy(rhs.begin(), rhs.end());free();elements = data.first;first_free = cap = data.second;return *this;
}void StrVec::alloc_n_move(size_t new_cap)
{auto newdata = alloc.allocate(new_cap);auto dest = newdata;auto elem = elements;for (size_t i = 0; i != size(); ++i)alloc.construct(dest++, std::move(*elem++));free();elements = newdata;first_free = dest;cap = elements + new_cap;
}void StrVec::reallocate()
{auto newcapacity = size() ? 2 * size() : 1;alloc_n_move(newcapacity);
}void StrVec::reserve(size_t new_cap)
{if (new_cap <= capacity()) return;alloc_n_move(new_cap);
}void StrVec::resize(size_t count)
{resize(count, std::string());
}void StrVec::resize(size_t count, const std::string &s)
{if (count > size()){if (count > capacity()) reserve(count * 2);for (size_t i = size(); i != count; ++i)alloc.construct(first_free++, s);}else if (count < size()){while (first_free != elements + count)alloc.destroy(--first_free);}
}StrVec::StrVec(StrVec &&s) NOEXCEPT : elements(s.elements), first_free(s.first_free), cap(s.cap)
{// leave s in a state in which it is safe to run the destructor.s.elements = s.first_free = s.cap = nullptr;
}StrVec& StrVec::operator = (StrVec &&rhs) NOEXCEPT
{if (this != &rhs){free();elements = rhs.elements;first_free = rhs.first_free;cap = rhs.cap;rhs.elements = rhs.first_free = rhs.cap = nullptr;}return *this;
}bool operator==(const StrVec &lhs, const StrVec &rhs)
{return (lhs.size() == rhs.size() && std::equal(lhs.begin(), lhs.end(), rhs.begin()));
}bool operator!=(const StrVec &lhs, const StrVec &rhs)
{return !(lhs == rhs);
}bool operator<(const StrVec &lhs, const StrVec &rhs)
{return std::lexicographical_compare(lhs.begin(), lhs.end(), rhs.begin(), rhs.end());
}bool operator>(const StrVec &lhs, const StrVec &rhs)
{return rhs < lhs;
}bool operator<=(const StrVec &lhs, const StrVec &rhs)
{return !(rhs < lhs);
}bool operator>=(const StrVec &lhs, const StrVec &rhs)
{return !(lhs < rhs);
}StrVec& StrVec::operator=(std::initializer_list<std::string> il)
{*this = StrVec(il);return *this;
}
练习14.24
你在7.5.1节的练习7.40中曾经选择并编写了一个类,你认为它应该含有拷贝赋值和移动赋值运算符吗?如果是,请实现它们。
头文件
#ifndef DATE_H
#define DATE_H#ifndef _MSC_VER
#define NOEXCEPT noexcept
#else
#define NOEXCEPT
#endif#include <iostream>
#include <vector>class Date
{friend bool operator ==(const Date& lhs, const Date& rhs);friend bool operator < (const Date &lhs, const Date &rhs);friend bool check(const Date &d);friend std::ostream& operator <<(std::ostream& os, const Date& d);
public:typedef std::size_t Size;// default constructorDate() = default;// constructor taking Size as daysexplicit Date(Size days);// constructor taking three SizeDate(Size d, Size m, Size y) : day(d), month(m), year(y) {}// constructor taking iostreamDate(std::istream &is, std::ostream &os);// copy constructorDate(const Date& d);// move constructorDate(Date&& d) NOEXCEPT;// copy operator=Date& operator= (const Date& d);// move operator=Date& operator= (Date&& rhs) NOEXCEPT;// destructor -- in this case, user-defined destructor is not nessary.~Date() { std::cout << "destroying\n"; }// membersSize toDays() const; //not implemented yet.Date& operator +=(Size offset);Date& operator -=(Size offset);private:Size day = 1;Size month = 1;Size year = 0;
};static const Date::Size YtoD_400 = 146097; //365*400 + 400/4 -3 == 146097
static const Date::Size YtoD_100 = 36524; //365*100 + 100/4 -1 == 36524
static const Date::Size YtoD_4 = 1461; //365*4 + 1 == 1461
static const Date::Size YtoD_1 = 365; //365// normal year
static const std::vector<Date::Size> monthsVec_n =
{ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };// leap year
static const std::vector<Date::Size> monthsVec_l =
{ 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };// non-member operators: << >> - == != < <= > >=
//
std::ostream&
operator <<(std::ostream& os, const Date& d);
std::istream&
operator >>(std::istream& is, Date& d);
int
operator - (const Date& lhs, const Date& rhs);
bool
operator ==(const Date& lhs, const Date& rhs);
bool
operator !=(const Date& lhs, const Date& rhs);
bool
operator < (const Date& lhs, const Date& rhs);
bool
operator <=(const Date& lhs, const Date& rhs);
bool
operator >(const Date& lhs, const Date& rhs);
bool
operator >=(const Date& lhs, const Date& rhs);
Date
operator - (const Date& lhs, Date::Size rhs);
Date
operator +(const Date& lhs, Date::Size rhs);// utillities:
bool check(const Date &d);
inline bool
isLeapYear(Date::Size y);// check if the date object passed in is valid
inline bool
check(const Date &d)
{if (d.month == 0 || d.month >12)return false;else{// month == 1 3 5 7 8 10 12if (d.month == 1 || d.month == 3 || d.month == 5 || d.month == 7 ||d.month == 8 || d.month == 10 || d.month == 12){if (d.day == 0 || d.day > 31) return false;elsereturn true;}else{// month == 4 6 9 11if (d.month == 4 || d.month == 6 || d.month == 9 || d.month == 11){if (d.day == 0 || d.day > 30) return false;elsereturn true;}else{// month == 2if (isLeapYear(d.year)){if (d.day == 0 || d.day >29) return false;elsereturn true;}else{if (d.day == 0 || d.day >28) return false;elsereturn true;}}}}
}inline bool
isLeapYear(Date::Size y)
{if (!(y % 400)){return true;}else{if (!(y % 100)){return false;}elsereturn !(y % 4);}
}
#endif // DATE_H
CPP文件
#include "exercise14_24.h"
#include <algorithm>// constructor taking Size as days
// the argument must be within (0, 2^32)
Date::Date(Size days)
{// calculate the yearSize y400 = days / YtoD_400;Size y100 = (days - y400*YtoD_400) / YtoD_100;Size y4 = (days - y400*YtoD_400 - y100*YtoD_100) / YtoD_4;Size y = (days - y400*YtoD_400 - y100*YtoD_100 - y4*YtoD_4) / 365;Size d = days - y400*YtoD_400 - y100*YtoD_100 - y4*YtoD_4 - y * 365;this->year = y400 * 400 + y100 * 100 + y4 * 4 + y;// check if leap and choose the months vector accordinglystd::vector<Size>currYear= isLeapYear(this->year) ? monthsVec_l : monthsVec_n;// calculate day and month using find_if + lambdaSize D_accumu = 0, M_accumu = 0;// @bug fixed: the variabbles above hade been declared inside the find_if as static// which caused the bug. It works fine now after being move outside.std::find_if(currYear.cbegin(), currYear.cend(), [&](Size m){D_accumu += m;M_accumu++;if (d < D_accumu){this->month = M_accumu;this->day = d + m - D_accumu;return true;}elsereturn false;});
}// construcotr taking iostream
Date::Date(std::istream &is, std::ostream &os)
{is >> day >> month >> year;if (is){if (check(*this)) return;else{os << "Invalid input! Object is default initialized.";*this = Date();}}else{os << "Invalid input! Object is default initialized.";*this = Date();}}// copy constructor
Date::Date(const Date &d) :
day(d.day), month(d.month), year(d.year)
{}// move constructor
Date::Date(Date&& d) NOEXCEPT :
day(d.day), month(d.month), year(d.year)
{ std::cout << "copy moving"; }// copy operator=
Date &Date::operator= (const Date &d)
{this->day = d.day;this->month = d.month;this->year = d.year;return *this;
}// move operator=
Date &Date::operator =(Date&& rhs) NOEXCEPT
{if (this != &rhs){this->day = rhs.day;this->month = rhs.month;this->year = rhs.year;}std::cout << "moving =";return *this;
}// conver to days
Date::Size Date::toDays() const
{Size result = this->day;// check if leap and choose the months vector accordinglystd::vector<Size>currYear= isLeapYear(this->year) ? monthsVec_l : monthsVec_n;// calculate result + days by monthsfor (auto it = currYear.cbegin(); it != currYear.cbegin() + this->month - 1; ++it)result += *it;// calculate result + days by yearsresult += (this->year / 400) * YtoD_400;result += (this->year % 400 / 100) * YtoD_100;result += (this->year % 100 / 4) * YtoD_4;result += (this->year % 4) * YtoD_1;return result;
}// member operators: += -=Date &Date::operator +=(Date::Size offset)
{*this = Date(this->toDays() + offset);return *this;
}Date &Date::operator -=(Date::Size offset)
{if (this->toDays() > offset)*this = Date(this->toDays() - offset);else*this = Date();return *this;
}// non-member operators: << >> - == != < <= > >=std::ostream&
operator <<(std::ostream& os, const Date& d)
{os << d.day << " " << d.month << " " << d.year;return os;
}std::istream&
operator >>(std::istream& is, Date& d)
{if (is){Date input = Date(is, std::cout);if (check(input)) d = input;}return is;
}int operator -(const Date &lhs, const Date &rhs)
{return lhs.toDays() - rhs.toDays();
}bool operator ==(const Date &lhs, const Date &rhs)
{return (lhs.day == rhs.day) &&(lhs.month == rhs.month) &&(lhs.year == rhs.year);
}bool operator !=(const Date &lhs, const Date &rhs)
{return !(lhs == rhs);
}bool operator < (const Date &lhs, const Date &rhs)
{return lhs.toDays() < rhs.toDays();
}bool operator <=(const Date &lhs, const Date &rhs)
{return (lhs < rhs) || (lhs == rhs);
}bool operator >(const Date &lhs, const Date &rhs)
{return !(lhs <= rhs);
}bool operator >=(const Date &lhs, const Date &rhs)
{return !(lhs < rhs);
}Date operator - (const Date &lhs, Date::Size rhs)
{ // ^^^ rhs must not be larger than 2^32-1// copy lhsDate result(lhs);result -= rhs;return result;
}Date operator + (const Date &lhs, Date::Size rhs)
{ // ^^^ rhs must not be larger than 2^32-1// copy lhsDate result(lhs);result += rhs;return result;
}
练习14.25
上题的这个类还需要定义其他赋值运算符吗?如果是,请实现它们;同时说明运算对象应该是什么类型并解释原因。
是。如上题。
练习14.26
为你的 StrBlob 类、StrBlobPtr 类、StrVec 类和 String 类定义下标运算符。
练习14.27
为你的 StrBlobPtr 类添加递增和递减运算符。
练习14.28
为你的 StrBlobPtr 类添加加法和减法运算符,使其可以实现指针的算术运算。
练习14.29
为什么不定义const 版本的递增和递减运算符?
因为递增和递减会改变对象本身,所以定义 const 版本的毫无意义。
练习14.30
为你的 StrBlobPtr 类和在12.1.6节练习12.22中定义的 ConstStrBlobPtr 的类分别添加解引用运算符和箭头运算符。注意:因为 ConstStrBlobPtr 的数据成员指向const vector,所以ConstStrBlobPtr 中的运算符必须返回常量引用。