[英]c++ primer - value of variables
我开始阅读C++ Primer,第 5 版,但对于std::cin
,我很难理解一件事。
以下是他们作为示例提供的代码。 其背后的想法是书店正在记录其交易,只要它们属于同一本书(即它们具有相同的 isbn),程序就应该能够对背靠背的交易求和。
我没有包含 header 文件,因为我认为它与我的问题无关。 如果确实需要它,您可以在此处找到它。
我对这个例子的问题是,解释代码的注释说第一个Sales_item
object,名为total
,用于存储当前交易,而名为trans
的交易用于“保存运行总和”。 也就是总。
#include <iostream>
#include "Sales_item.h"
int main()
{
Sales_item total; // variable to hold data for the next transaction
// read the first transaction and ensure that there are data to process
if (std::cin >> total) {
Sales_item trans; // variable to hold the running sum
// read and process the remaining transactions
while (std::cin >> trans) {
// if we're still processing the same book
if (total.isbn() == trans.isbn())
total += trans; // update the running total
else {
// print results for the previous book
std::cout << total << std::endl;
total = trans; // total now refers to the next book
}
}
std::cout << total << std::endl; // print the last transaction
} else {
// no input! warn the user
std::cerr << "No data?!" << std::endl;
return -1; // indicate failure
}
return 0;
}
我已经看到了各种具有这种推理的例子,对我来说这看起来违反直觉。 第一个变量不应该持有总数(因为它属于更广泛的 scope 并且它被命名为total
)而第二个持有当前交易? 我是否完全理解了这一点,而第二个cin
实际上持有总数?
我同意,评论似乎被交换了。 他们应该是:
Sales_item total; // variable to hold the running sum
Sales_item trans; // variable to hold data for the next transaction
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.