c++ - 为什么要返回通过引用传递给 C++ 中的函数的对象?

标签 c++ pass-by-reference

在 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/

相关文章:

matlab - 通过按向左和向右箭头键为 MATLAB 图制作动画

c++ - 具有许多成员变量的类的最佳实践

c++ - Qt中是否有签名的 `sizeof`替代品

android - 无法在android上使用C++ OpenCV打开相机

java - 数组似乎在 Java 中通过引用传递,这怎么可能?

c - C 中的输出参数

c++ - C++ 类方法的 Emacs 缩进?

c++ - LLVM libc++ 无法在 Mac OS 上使用 clang 3.3 进行编译

c - 在 C 中使用数组参数是否被认为是不好的做法?

对结构的 C 代码引用