c++ - 返回形式参数的引用

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

问题:

我的期望是为变量 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/

相关文章:

c++ - 如何将元素从 C++11 容器移动到容器的背面?

c++ - 将项目小部件宽度(列表内容)调整为父 QListWidget 宽度

c++ - libsvm svm_node 和 svm_predict

c++ - 帮助模板化字节交换功能,性能受到影响?

c++ - 传递定义二维数组元素大小的变量

C++ 错误 : unable to find string literal operator

c++ - 如何使用 .运算符(operator)

c++ - 为什么C++中有全局变量?

c++ - 具有多个继承共享一个资源的对象 - 寻找好的设计模式

c++ - 无法填充动态类模板数组