首页 > 代码库 > Sales_item例子
Sales_item例子
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;}
运行结果如下:
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。