"&"符号在函数的返回类型中是什么意思?

What does the "&" symbol mean in the return type of a function?

本文关键字:是什么 意思 返回类型 符号 函数      更新时间:2023-10-16

我正在读一本C++书,它解释了以下函数:

istream& read_hw(istream& in, vector<double>& hw) {
    if (in) {
        hw.clear() ;
        double x;
        while (in >> x)
            hw.push_back(x);
        in.clear();
    }
    return in;
}

这本书解释说,参数列表中的"&"意味着它们是通过引用传递的,但在函数的返回类型中,istream&中没有关于该符号的解释
删除它会导致许多编译错误。有人能澄清吗?

函数也通过引用返回。在这种情况下,您传入的对象是从函数返回的,因此您可以"连锁"调用此函数:

in.read_hw(hw1).read_hw(hw2);

这是C++中常见的模式,尤其是在使用IOstreams库时。

这将返回对istream的引用。注意,这可能与istream&作为参数传递的引用。

来自learncpp.com:

通过引用返回通常用于将通过引用传递给函数的参数返回给调用方。在下面的例子中,我们(通过引用)返回一个数组的元素,该元素通过引用传递给我们的函数:

// This struct holds an array of 25 integers
struct FixedArray25
{
    int anValue[25];
};
// Returns a reference to the nIndex element of rArray
int& Value(FixedArray25 &rArray, int nIndex)
{
    return rArray.anValue[nIndex];
}
int main()
{
    FixedArray25 sMyArray;
    // Set the 10th element of sMyArray to the value 5
    Value(sMyArray, 10) = 5;
    cout << sMyArray.anValue[10] << endl;
    return 0;
}

在"istream&in"中;操作员的意思是"的参考"

只要知道,无论你在这里传递什么变量,原始值都会被修改

它是一个引用。它就像一个指针,但不能为NULL。

因此,您的函数返回对istream对象的引用。请注意,您还向函数传递了与第一个参数相同的数据类型。

对流执行此操作非常常见,因此您可以使用流测试运算符来检查错误条件:

if( !read_hw(in, hw) ) cerr << "Read failedn";