在 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;
}
最佳答案
它允许你编写流畅的界面,就像这样
read_hw(cin, hw).read_something_else(cin, x).blah_blah(cin, y)
由于每个方法调用都会返回对 istream
对象的引用,因此它可用于链接方法调用。
事实上,当你这样做时会发生什么
cin >> a >> b;
每个 operator>>
函数调用都会返回对流的引用,因此它可以被链接起来。
它还可以让您循环并从 istream
对象中读取 idiomatic way in C++ , 例如
while (read_hw(cin, hw)) {
do_something_with_hw(hw);
}
关于c++ - 为什么要返回通过引用传递给 C++ 中的函数的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44466422/