参考函数如何“int& foo();”工作?

时间:2018-05-17 15:06:43

标签: c++ function reference

我不确定你是否称它为“参考函数”,但是我的老师向我们展示了一个代码,它声明了一个像引用变量这样的函数,但我没有得到它背后的逻辑。

#include <iostream>
using namespace std;

int &max(int &x, int &y)
{
    if(x > y)
        return x;
    return y;
}

int main()
{
    int x, y;
    cout << "Enter 2 #s";
    cin >> x >> y;

    y = 3;
    max(x, y) = 1000;

    cout << endl;
    cout << "X: " << x << endl;
    cout << "Y: " << y << endl;
    cout << max(x, y) << endl; 

    max(x, y) = 1000;
    x = 5;

    cout << endl;
    cout << "X: " << x << endl;
    cout << "Y: " << y << endl;
    cout << max(x, y) << endl; 
}

3 个答案:

答案 0 :(得分:3)

它不是引用函数,而是在表达式

中返回对x或y的引用
return x;

return y;

通过注意到你在问题中给出的定义等同于以下表达式,&amp;写在int而不是max。

旁边
int& max(int &x, int &y)
{
    if(x > y)
        return x;
    return y;
}

答案 1 :(得分:2)

它不是参考函数,但函数的返回值是引用。您可以像这样阅读函数:reaction_added。以下是更多信息:https://www.tutorialspoint.com/cplusplus/returning_values_by_reference.htm

答案 2 :(得分:0)

我认为命名法意味着该函数将返回对整数的引用。究竟是怎么做到的,我真的不知道。我不习惯看到以这种方式声明的函数,我可能会完全改变声明。