14.1
不同点:重载运算符至少有一个操作数是类类型,而且对于部分运算符它无法保留求值顺序或短路求值属性
相同点:对于一个重载运算符来说,其优先级和结合律与对应的内置运算符保持一致
14.2
1 #include <iostream> 2 #include <vector> 3 #include <string> 4 5 using namespace std; 6 7 class Sales_data { 8 friend istream &operator>>(istream &is, Sales_data&); 9 friend ostream &operator<<(ostream &os, Sales_data&); 10 public: 11 //构造函数 12 Sales_data() = default; 13 //重载运算符 14 Sales_data &operator+=(const Sales_data&); 15 private: 16 string bookNo; //书的ISBN 17 unsigned units_sold = 0; //售出的本数 18 double revenue = 0.0; //销售额 19 }; 20 21 istream &operator>>(istream &is, Sales_data &book) 22 { 23 is >> book.bookNo >> book.units_sold >> book.revenue; 24 return is; 25 } 26 27 ostream &operator<<(ostream &os, Sales_data &book) 28 { 29 os << book.bookNo << " " << book.units_sold << " " << book.revenue; 30 return os; 31 } 32 33 Sales_data &Sales_data::operator+=(const Sales_data &rhs) 34 { 35 units_sold += rhs.units_sold; 36 revenue += rhs.revenue; 37 return *this; 38 } 39 40 Sales_data operator+(const Sales_data &lhs, const Sales_data &rhs) 41 { 42 Sales_data total = lhs; 43 total += rhs; 44 return total; 45 } 46 47 48 int main() 49 { 50 Sales_data a; 51 cin >> a; 52 Sales_data b, c; 53 b = a; 54 c = a + b; 55 cout << a << endl << b << endl << c << endl; 56 return 0; 57 }