输出操作符
//output operator redefined
ostream& operator<<(ostream& out, const Sales_item& s) { //line break(\n) not allowed, tab(\t) used instead out << s.isbn << "\t" << s.units_sold << "\t" << s.revenue << "\t" << s.avg_prive(); }
输入操作符
//redefine of input operator istream& operator>> (istream& in, Sales_item& si) { in >> si.isbn >> si.units_sold; //check that the inputs succeed if(in) s.revenue = s.units_sold * price; else s = Sales_item(); //input failed:rest object to default state return in; }
vector and >> operator
class CheckoutRecord{ friend istream& operator>> (istream& in, CheckoutRecord cc); public: private: double bookId; string title; string dateBorrowed; //Date uncertain, use string instead. pair<string,string> borrower; vector<pair<string,string>* > waitList; }; //redefine >> for CheckoutRecord istream& operator>> (istream& in, CheckoutRecord cc) { in >> cc.bookId >> cc.title >> cc.dateBorrowed >> cc.borrower.first >> cc.borrower.second; //check that the input succeed if(!in) { cc = CheckoutRecord(); //input failed: reset object to default state return in; } //clear vector context before input. // copy in answer; I can not see the necessary. cc.waitList.clear(); while(in) { pair<string,string>* pt = new pair<string,string>; //pointer type members in vector , should be built dynamically. in >> pt->first >> pt->second; if(!in) return in; //wrong input will break the loop. cc.waitList.push_back(pt); } return in; }
vector, assign opeator
//clear vector context waitList.clear(); for( vector< pair<string,string>* >::const_iterator beg = other.waitList.begin(); beg != other.waitList.end(); ++beg) { //as point type, need to alocate space to the pointer pair<string,string>* p = new pair<string,string>; *p = **beg; //deep copy, to avoid memory access, copy the value context, instead of the pointer waitList.push_back( p ); } return *this;