c++ - 如何引用函数“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;
}
解决方案
它不是引用函数,而是在表达式中返回对 x 或 y 的引用
return x;
和
return y;
通过注意到您在问题中给出的定义等同于以下表达式,其中 & 写在 int 旁边而不是 max 旁边,您可能会更清楚这一点。
int& max(int &x, int &y)
{
if(x > y)
return x;
return y;
}
推荐阅读
- binding - 如何自动重写 bindgen 创建的 FFI 函数的签名?
- css - 如何在移动设备上重新排序引导列?
- json - 如何打开单曲
> 到流动 ? - ios - gmsmapview 中的动画折线
- schemacrawler - 如何使用 schemacrawler 提取表上的基本描述性统计信息
- python - 在python中永久设置种子
- reactjs - 我需要帮助在反应中实现用户信息弹出窗口吗?
- android - 添加应用内更新后的 AbstractMethodError
- api - 如何在列表视图中查看来自 odoo api 的已解析 json 数据?
- python - Pandas 读取 CSV 和 Seaborn - ValueError:无法解释输入