Sales_item.h
#ifndef SALES_ITEM_H #define SALES_ITEM_H #include<iostream> #include<string> using namespace std; class Sales_item { friend ostream& operator<<(ostream &os,const Sales_item &); friend istream& operator>>(istream &is,Sales_item &); private: string bookno; unsigned units_sold=0; double revenue=0.0; public: string isbn()const { return this->bookno; } double avg_price() const; Sales_item& operator=(const Sales_item &); Sales_item& operator+(const Sales_item &); Sales_item& operator+=(const Sales_item &); }; #endif // SALES_ITEM_H
Sales_item.cpp
#include "Sales_item.h" istream& operator>>(istream &in,Sales_item &s) { double price; in>>s.bookno>>s.units_sold>>price; if(in) s.revenue=s.units_sold*price; else s=Sales_item(); return in; } ostream& operator<<(ostream &out,const Sales_item &s) { out<<s.isbn()<<" "<<s.units_sold<<" "<<s.revenue<<" "<<s.avg_price()<<endl; return out; } double Sales_item::avg_price() const { if(units_sold) return revenue/units_sold; else return 0; } Sales_item& Sales_item::operator=(const Sales_item &s) { units_sold=s.units_sold; revenue=s.revenue; isbn()=s.isbn(); return *this; } Sales_item& Sales_item::operator+(const Sales_item &s) { if(this->isbn()==s.isbn()) { units_sold+=s.units_sold; revenue+=s.revenue; } return *this; } Sales_item& Sales_item::operator+=(const Sales_item &s) { units_sold+=s.units_sold; revenue+=s.revenue; return *this; }
useSales_item.cpp
#include"Sales_item.h" int main() { Sales_item book; cin>>book; cout<<book<<endl; Sales_item item1,item2; cin>>item1>>item2; cout<<item1+item2<<endl; return 0; }
运行结果如下:
Sales_item例子
时间: 2024-10-08 10:00:16