本文主要是介绍7.1.2 定义改进的Sales_data类,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
练习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;elsereturn 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
这篇关于7.1.2 定义改进的Sales_data类的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!