#include <iostream> #include <string> #include <cassert> #include <algorithm> #include <vector> using namespace std; 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&);//非成员函数(对称性) friend bool operator==(const Sales_data&,const Sales_data&); friend bool operator!=(const Sales_data&,const Sales_data&); public: Sales_data():units_sold(0),revenue(0.0){} Sales_data(const std::string &s):bookNo(s),units_sold(0),revenue(0.0){} Sales_data(const std::string &s,unsigned n,double p):bookNo(s),units_sold(n),revenue(n*p){} Sales_data(std::istream &is); Sales_data& operator+=(const Sales_data&);//成员函数(复合赋值一般是成员函数) std::string isbn()const{return bookNo;} Sales_data& operator=(const std::string &s); private: inline double avg_price()const;//inline private: std::string bookNo; //isbn unsigned units_sold;//销售量 double revenue; //总价 }; inline double Sales_data::avg_price() const { return units_sold ? revenue/units_sold : 0; } Sales_data::Sales_data(std::istream &is) { is>>*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=item.units_sold*price; else item=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& item1,const Sales_data& item2) { Sales_data s(item1); s+=item2;//调用复合赋值 return s; } Sales_data& Sales_data::operator+=(const Sales_data& rhs) { units_sold+=rhs.units_sold; revenue+=rhs.revenue; return *this; } bool operator==(const Sales_data& lhs,const Sales_data& rhs) { return lhs.bookNo==rhs.bookNo && lhs.units_sold==rhs.units_sold && lhs.revenue==rhs.revenue; } bool operator!=(const Sales_data& lhs,const Sales_data& rhs) { return !(lhs==rhs); } Sales_data& Sales_data::operator=(const std::string &s) { *this=Sales_data(s); return *this; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-12-22 18:39:39