如果这是非常基本的问题,请放轻松。
从函数返回引用,我可以看到一些好处,比如。这是伪代码。
int myarr[] = { ..... }
int & myfunction(int index)
{
return myarr[index]
}
myfunction(1) = 20; // sets the value to myarr[1].
我尝试了以下代码:
#include <iostream>
using namespace std;
int & topper (int & x, int & y)
{
return (x>y)?x:y;
}
int main()
{
int a=10, b=20;
int c;
c=topper(a,b);
cout <<"Topper "<<c<<endl;
c=100;
cout <<" a value is "<<a<<endl;
return 0;
}
问题:
我的期望是为变量 a
打印 100
。我将 a
的引用传递给 topper()
函数,并返回与 a
相同的引用,并分配给 c
.
我确定我遗漏了一些要点,当我们声明 int c
时,它不应该是不同的内存位置,而应该指向返回 c
值(value)到不同的位置,但我们必须做一个引用。
最佳答案
and returns the same reference of 'a', and assign to 'c'.
是的,您通过引用返回 b
(不是 a
),但是您通过将它分配给 c
值,因此您可以将代码更改为:
int & c = topper(a, b);
cout << "Topper " << c << endl;
c = 100;
cout << " b value is "<< b << endl;
关于c++ - 返回形式参数的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24879671/