繁体   English   中英

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

[英]What does the “&” symbol mean in the return type of a 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;
}

该书解释了参数列表中的“&”表示它们是通过引用传递的,但是在函数的返回类型中, 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&中”中,&运算符表示“的引用”

只是知道无论您在此处传递什么变量,原始值都会被修改

这是一个参考。 它就像一个指针,但不能为NULL。

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

对流执行此操作非常普遍,因此您可以使用流测试操作符来检查错误情况:

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

暂无
暂无

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

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