c++ - 引用函数 "int &foo();"是如何工作的?

标签 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; 
}

最佳答案

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

return x;

return y;

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

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

关于c++ - 引用函数 "int &foo();"是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50394776/

相关文章:

c++ - 无法在qt之外运行应用程序

function - 我可以根据不同参数的 _value_ 强制一个参数吗?

arrays - 如何在 Perl 中正确传递引用和嵌套引用

c++ - 在这种情况下,有人可以解释 "reference"和 "pointer"之间的区别吗?

java - 通过搜索引用java删除节点

c++ - 同名功能的错误检测

c++ - 在结构体中使用 union 的目的是什么?

c++ - 为什么 std::string 引用不能带 char*?

c - 从函数到主函数使用字符串

jQuery 调用预定义函数