C++ Primer(第5版) 练习 14.9

练习 14.9 为你的Sales_data类定义输入运算符。

环境:Linux Ubuntu(云服务器)
工具:vim

 

代码块
/*************************************************************************
	> File Name: ex14.9.cpp
	> Author: 
	> Mail: 
	> Created Time: Tue 30 Apr 2024 08:20:50 AM CST
 ************************************************************************/

#include<iostream>
using namespace std;

struct Sales_data{
    Sales_data(const string &s, unsigned n, double p):
                bookNo(s), units_sold(n), price(p), revenue(p * n) {}
    Sales_data(): Sales_data("", 0, 0) {}
    Sales_data(string s): Sales_data(s, 0, 0) {}
    
    friend istream &operator>>(istream &, Sales_data &);
    friend ostream &operator<<(ostream &, const Sales_data &);
    
    Sales_data& operator+= (Sales_data &);
    
    string isbn() const;
    Sales_data& combine(const Sales_data&);
    double avg_price() const;

    string bookNo;
    unsigned units_sold = 0;
    double price = 0.0;
    double revenue = 0.0;
};

string Sales_data::isbn() const{
    return this->bookNo;
}

Sales_data& Sales_data::combine(const Sales_data &rhs){
    units_sold += rhs.units_sold;
    revenue += rhs.revenue;
    price = rhs.price;
    bookNo = rhs.bookNo;
    return *this;
}

double Sales_data::avg_price() const{
    if(units_sold){
        return revenue / units_sold;
    }
    else{
        return 0;
    }
}

Sales_data& Sales_data::operator+= (Sales_data &sd){
    this->combine(sd);
    return *this;
}

ostream &operator<<(ostream &output, const Sales_data &sd){
    output<<sd.bookNo<<" "<<sd.units_sold<<" "<<sd.price<<" "<<sd.revenue<<" "<<sd.avg_price()<<endl;
    return output;
}

istream &operator>>(istream &input, Sales_data &sd){
    input>>sd.bookNo>>sd.units_sold>>sd.price;
    sd.revenue = sd.price * sd.units_sold;
    return input;
}

int main(){
    Sales_data  book2, book4;
    cout<<"Enter book4: ";
    cin>>book4;

    book2 += book4;
    cout<<"Book2: "<<book2<<endl;

    return 0;
}
05-05 09:50