1 #include <iostream> 2 #include <string> 3 4 using namespace std; 5 //重载操作符 6 //定义的方式是operator*() 重载*运算符 7 8 class Sales_item 9 { 10 friend ostream &operator<<(ostream &out,const Sales_item &s); 11 friend istream &operator>>(istream &in,Sales_item &s); 12 friend bool operator==(const Sales_item &,const Sales_item &); 13 public: 14 Sales_item(string &book,unsigned units,double price): 15 isbn(book), 16 units_sold(units), 17 revenue(units*price){} 18 Sales_item(): 19 units_sold(0), 20 revenue(0.0){} 21 //重载+=运算符 一般设置为成员函数 ,因为修改了当前对象 22 Sales_item &operator+=(const Sales_item &); 23 public: 24 double avg_price() const; 25 // bool same_isbn(const Sales_item &rsh) 26 // { 27 // return isbn==rsh.isbn; 28 // } 29 private: 30 string isbn; 31 unsigned units_sold; 32 double revenue; 33 }; 34 //计算书的平均价格 35 inline double Sales_item::avg_price() const 36 { 37 if(units_sold) 38 { 39 return revenue/units_sold; 40 }else{ 41 return 0; 42 } 43 } 44 //重载==和!=运算符 45 inline bool operator==(const Sales_item &lsh,const Sales_item &rsh) 46 { 47 return lsh.isbn==rsh.isbn && lsh.units_sold==rsh.units_sold && lsh.revenue==rsh.revenue; 48 } 49 bool operator!=(const Sales_item &lsh,const Sales_item &rsh) 50 { 51 //让一个操作符调用另外一个操作符 52 return !(lsh==rsh); 53 } 54 //重载+=操作符 55 Sales_item& Sales_item::operator+=(const Sales_item &s) 56 { 57 this->units_sold+=s.units_sold; 58 this->revenue+=s.revenue; 59 return *this; 60 } 61 //重载加法操作符 一把不设置为成员函数 62 Sales_item operator+(const Sales_item &s1,const Sales_item &s2) 63 { 64 //将第一个参数进行实现用于返回结果 65 Sales_item ret(s1); 66 ret+=s2; 67 return ret; 68 69 } 70 //重载输出操作符 71 ostream &operator<<(ostream &out,const Sales_item &s) 72 { 73 out<<s.isbn<<"--"<<s.units_sold<<"--"<<s.revenue; 74 return out; 75 } 76 //重载输入操作符 77 istream &operator>>(istream &in,Sales_item &s) 78 { 79 double price; 80 in>>s.isbn>>s.units_sold>>price; 81 //输入的时候进行错误检查 如果出错就创建一个新的订单 82 if(in) 83 { 84 s.revenue=s.units_sold*price; 85 }else{ 86 s=Sales_item(); 87 } 88 89 return in; 90 } 91 92 int main() 93 { 94 string s("1-001-2543"); 95 // Sales_item item1(s,25,2.50); 96 // cout<<item1<<endl; 97 // cin>>item1; 98 // cout<<item1<<endl; 99 // Sales_item item2(s,10,120.0); 100 // Sales_item item3(s,20,200.0); 101 // Sales_item ret=item2+item3; 102 // cout<<ret<<endl; 103 // 104 // Sales_item item4(s,20,200); 105 // item4+=item4; 106 // cout<<item4<<endl; 107 // Sales_item a(s,10,120.0); 108 // Sales_item b(s,10,120.0); 109 // Sales_item c(s,20,110.0); 110 // if(a==b) 111 // { 112 // cout<<"a和b是一个订单"<<endl; 113 // } 114 // if(a!=c) 115 // { 116 // cout<<"a和c不是一个订单"<<endl; 117 // } 118 119 120 return 0; 121 }