简体   繁体   English

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

[英]What does the “&” symbol mean in the return type of a function?

I'm reading a C++ book that explains the following function: 我正在读一本解释以下功能的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;
}

The book explained those "&" in the arguments list mean they are passed by reference, but there is no explanation about that symbol in istream& : in the return type of the function. 该书解释了参数列表中的“&”表示它们是通过引用传递的,但是在函数的返回类型中, istream&没有关于该符号的解释:
Removing it causes many compilation errors. 删除它会导致许多编译错误。 Can someone clarify? 有人可以澄清吗?

The function returns by reference as well. 该函数也通过引用返回。 In this case, the object you pass in is returned from the function, so you can "chain" calls to this function: 在这种情况下,您传入的对象是从函数返回的,因此您可以“链接”对此函数的调用:

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

This is a common pattern in C++, especially when in with the IOstreams library. 这是C ++中的常见模式,尤其是与IOstreams库一起使用时。

This is returning a reference to the istream. 这将返回对istream的引用。 Note that this is probably the same as the istream& reference passed as an argument. 请注意,这可能与作为参数传递的istream&引用相同。

From learncpp.com : learncpp.com

Return by reference is typically used to return arguments passed by reference to the function back to the caller. 按引用返回通常用于将通过引用传递给函数的参数返回给调用者。 In the following example, we return (by reference) an element of an array that was passed to our function by reference: 在下面的示例中,我们返回(通过引用)通过引用传递给函数的数组元素:

// 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;
}

in "istream& in" the & operator means "the reference of" 在“ istream&中”中,&运算符表示“的引用”

just know that whatever variable you pass into here, the original value will be modified 只是知道无论您在此处传递什么变量,原始值都会被修改

It is a reference. 这是一个参考。 It's like a pointer but it can't be NULL. 它就像一个指针,但不能为NULL。

So your function is returning a reference to an istream object. 因此,您的函数将返回对istream对象的引用。 Notice that you also pass the same data type as the first parameter to your function. 请注意,您还将与第一个参数相同的数据类型传递给函数。

It is quite common to do this with streams so you can use the stream test operator to check for error conditions: 对流执行此操作非常普遍,因此您可以使用流测试操作符来检查错误情况:

if( !read_hw(in, hw) ) cerr << "Read failed\n";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM