首页 > 解决方案 > 如何引用函数“int &foo();” 工作?

问题描述

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

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

标签: c++functionreference

解决方案


它不是引用函数,而是在表达式中返回对 x 或 y 的引用

return x;

return y;

通过注意到您在问题中给出的定义等同于以下表达式,其中 & 写在 int 旁边而不是 max 旁边,您可能会更清楚这一点。

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

推荐阅读