C++ Primer 7.33 练习编写成员函数

这里我们编写一个成员函数,可以实现两个sales_item相加。实现起来如下:

1.先在Sales_item.h中类定义里添加声明。

 Sales_item add(Sales_item& other);

2.再到Sales_item.cpp中实现该函数,记住函数名前要添加域Sales_item::。

//两组交易相加
Sales_item Sales_item::add(Sales_item& other)
{
    units_sold += other.units_sold;
    revenue += other.revenue;
    return *this;
}

3.为了测试效果,我们在主程序里编写如下代码:

//7-33.cpp
//读入一组交易,输出每本书的销售册数 总销售收入 和 平均销售价格
#include <iostream>
#include <Sales_item.h>
using namespace std;

int main()
{
    Sales_item total, trans;    //保存总和和下一笔交易

    cout << "Enter some transactions(Ctrl + Z to end):" << endl;
    if (total.input(cin))   //读入第一个记录有效
    {
        while (trans.input(cin))    //读入后续的交易
            if (total.same_isbn(trans))
                //新读入的交易有相同isbn则相加
                total.add(trans);
            else
                //不同则输出 total 并重置total
            {
                total.output(cout) << endl;;
                total = trans;
            }
        //输出最后一个total
        total.output(cout) << endl;;
    }
    else
    {
        cout << "No data?!" << endl;
        return -1;
    }
    return 0;
}


原文地址:https://www.cnblogs.com/mrbourne/p/9959464.html