C++ Primer(第5版)- Chapter 7. Classes -005
Using the Revised Sales_data Class
使用改进的Sales_data类
Before we think about how to implement our class, let’s look at how we can use our interface functions. As one example, we can use these functions to write a version of the bookstore program from § 1.6 (p. 24) that works with Sales_data objects rather than Sales_items:
在考虑如何实现我们的类之前,首先来看看应该如何使用上面这些接口函数。举个例子,我们能使用这些函数编写1.6节(第24页)书店程序的另外一个版本,这个程序使用Sales_data对象,不再使用Sales_items对象。
We start by defining a Sales_data object to hold the running total. Inside the if condition, we call read to read the first transaction into total. This condition works like other loops we’ve written that used the >> operator. Like the >> operator, our read function will return its stream parameter, which the condition checks (§ 4.11.2, p. 162). If the read fails, we fall through to the else to print an error message.
一开始我们定义了一个Sales_data对象用于保存实时汇总信息。在 if 条件内部,调用read函数将第一条交易读入到total中。这里的条件部分,与之前我们使用>>运算符的效果是一样的。read函数将返回他的流参数,而条件部分负责检查这个返回值(第4.11.2节,第162页)。如果read函数失败,程序将直接跳转到else语句并输出一条错误信息。
If there are data to read, we define trans, which we’ll use to hold each transaction. The condition in the while also checks the stream returned by read. So long as the input operations in read succeed, the condition succeeds and we have another transaction to process.
检测到有数据输入,我们定义变量trans用于保存每一个交易。while语句的条件部分同样会检查read函数的返回值。只要在函数read里的输入操作成功,条件就被满足,意味着我们可以处理一个新的交易。
Inside the while, we call the isbn members of total and trans to fetch their respective ISBNs. If total and trans refer to the same book, we call combine to add the components of trans into the running total in total. If trans represents a new book, we call print to print the total for the previous book. Because print returns a reference to its stream parameter, we can use the result of print as the left-hand operand of the <<. We do so to print a newline following the output generated by print. We next assign trans to total, thus setting up to process the records for the next book in the file.
在while循环内部,我们分别调用total和trans对象的成员函数isbn,来取得各自的ISBNs值。如果total和trans指示的是同一本书,我们调用combine函数将trans的内容添加到total的实时汇总信息中。如果trans指的是一本新书,我们调用print函数,输出前一本书的汇总信息。因为print函数返回的是它的流参数的引用,所以我们能用print的返回值作为<<运算符的左侧运算对象。通过这种方式,在输出print函数的处理结果后,然后转到下一行。接下来,把trans赋给total,从而为处理文件中下一本书的记录做好了准备。
After we have exhausted the input, we have to remember to print the data for the last transaction, which we do in the call to print following the while loop.
在处理完所有输入数据后,我们必须使用while循环语句后面的print函数,输出最后一个交易的数据信息。