练习14.6:为你的Sales_data类定义输出运算符。
// ConsoleApplication1.cpp : 定义控制台应用程序的入口点。
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Sales_data{
friend std::istream &read(std::istream&, Sales_data&);
friend std::istream &operator>>(istream &is, Sales_data&);
friend std::ostream &operator<<(std::ostream& os, Sales_data& item);
public:
Sales_data() = default;
Sales_data(const std::string &s, unsigned n, double p) :bookNo(s), units_sold(n), revenue(p*n){}
Sales_data(const std::string &s) :bookNo(s){}
Sales_data(std::istream&);
std::string isbn() const { return bookNo; }
private:
double avg_price() const
{
return units_sold ? revenue / units_sold : 0;
}
std::string bookNo;
unsigned units_sold = 0;
double revenue = 0.0;
};
Sales_data::Sales_data(std::istream& is){
read(is, *this);
}
istream &operator>>(std::istream& is, Sales_data& item){
double price = 0;
is >> item.bookNo >> item.units_sold >> price;
item.revenue = price * item.units_sold;
return is;
}
ostream &operator<<(std::ostream& os, Sales_data& item){
os << item.bookNo << item.units_sold << item.revenue << endl;
return os;
}
istream &read(istream &is, Sales_data &item){
double price = 0;
is >> item.bookNo >> item.units_sold >> price;
item.revenue = price * item.units_sold;
return is;
}
int _tmain(int argc, _TCHAR* argv[])
{
Sales_data a;
cin >> a;
cout << a;
return 0;
}
练习14.7:你在13.5节练习(第470页)中曾编写了一个string类,为它定义了一个输出运算符。