我不太确定你是否称它为“引用函数”,但我的老师向我们展示了一段代码,该代码声明了一个类似于引用变量的函数,但我不明白其背后的逻辑。
#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/