练习7.2
struct Sales_data {
//定义isbn成员函数
std::string isbn() const { return bookNo; }
//声明combine成员函数
Sales_data& combine(const Sales_data&);
//声明avg_price成员函数
double avg_price() const;
//其他数据成员
std::string bookNo;
unsigned units_sold = 0;
double revenue = 0;
};
练习7.3
double Sales_data::avg_price() const {
if (units_sold)
return revenue / units_sold;
else
return 0;
}
Sales_data& Sales_data::combine(const Sales_data& rhs)
{
units_sold += rhs.units_sold;
revenue += rhs.revenue;
return *this;
}
int main() {
Sales_data total;//保存下一条交易记录的变量
double price = 0.0;
//读入第一条交易记录,并确保有数据可以处理
if (cin >> total.bookNo >> total.units_sold >> price)
{
total.revenue = total.units_sold * price;
Sales_data trans;
while (cin >> trans.bookNo >> trans.units_sold >> price) {
//如果我们在处理相同的书
trans.revenue = trans.units_sold * price;
if (total.isbn() == trans.isbn()) {
total.combine(trans);
}
else {
//打印前一笔交易的次数
cout << "Result is " << total.bookNo << " " << total.units_sold << " " << total.revenue << endl;
total = trans;
}
}
cout << "Result is " << total.bookNo << " " << total.units_sold << " " << total.revenue << endl; //打印最后一笔交易的结果
}
else {
//没有输入
cerr << "No data?" << endl;
return -1;
}
return 0;
}
练习7.4
#ifndef SALES_DATA_H
#define SALES_DATA_H
#include <string>
using namespace std;
struct Person {
string pName() const { return name; }
string pAddress() const { return address; }
string name;
string address;
};
#endif