返回形式参数的引用

时间:2014-07-22 05:37:13

标签: c++

如果这是最基本的问题,请轻松告诉我。

从函数返回引用,我可以看到一些好处,如。这是伪代码。

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

问题:

我的期望是为变量100打印a。我将a的引用传递给topper()个函数,并返回a的相同引用,并分配给c

我确信我遗漏的一点是,当我们声明int c时,它不应该是一个不同的内存位置,而应该指向将c值返回到不同的位置但我们必须提供参考。

3 个答案:

答案 0 :(得分:2)

  

并返回&#39; a&#39;的相同引用,并分配给&#39; c&#39;。

是的,您通过引用返回b(而非a),但是您要按价值将其分配给c ,因此您可以将代码更改为:

int & c = topper(a, b);
cout << "Topper " << c << endl;
c = 100;
cout << " b value is "<< b << endl;

答案 1 :(得分:2)

你的问题很多混乱。

但是如果你想尝试别名变量c 指向a和b之间的顶部,尝试类似:

int& c = topper(a,b);

现在c是对topper返回的内容的引用 通过更改c,您可以更改topper返回的变量。

答案 2 :(得分:1)

你可以试试这个:

int &c = topper(a, b);

而不是

c=topper(a,b);

因为cint变量。

相关问题