【发布时间】:2017-11-11 23:32:40
【问题描述】:
在 Koenig 和 Moo 的 Accelerated C++ 一书第 57 页中,它们提供了如下所示的函数,该函数返回 in。这样做的规定原因是表明尝试的输入是否成功(第 55 页)。但是,in 是通过引用作为函数的参数之一传递的。那么你不能通过查看原始对象来获取 istream 的状态吗?
// read homework grades from an input stream into a `vector<double>'
istream& read_hw(istream& in, vector<double>& hw)
{
if (in) {
// get rid of previous contents
hw.clear();
// read homework grades
double x;
while (in >> x)
hw.push_back(x);
// clear the stream so that input will work for the next student
in.clear();
}
return in;
}
【问题讨论】:
-
可以,但
while (read_hw(s, data)) { ... }比while (s) { read_hw(s, data); if (s) {...}}好得多
标签: c++ pass-by-reference