函数何时必须在c ++中返回引用 [英] when does a function have to return a reference in c++

查看:43
本文介绍了函数何时必须在c ++中返回引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在c ++中,在什么情况下我们必须从函数返回引用?我知道将引用用作函数输入,但是对于函数输出,为什么我们不能仅返回值或指针?

In c++, under what scenarios do we have to return a reference from a function? I understand using references as function inputs, but for function outputs, why cannot we only return values or pointers?

推荐答案

参考文献用于为函数的返回值提供赋值.听起来很奇怪,但举个例子,c ++中的数组赋值运算符是一个实际上在index参数处返回对元素的引用的函数,因此可以将其赋给例如

References are used to provide assignment to return values of functions. Sounds odd, but as an example, the array assignment operator in c++ is a function that actually returns a reference to the element at the index parameter so that it can be assigned to, e.g.

class Array {
 public:
  int& operator[] (const int& index);
  ...
};

允许以下语法:

Array a;
a[4] = 192;

受到永远有用的C ++常见问题解答的启发:

Inspired by the eternally helpful C++ FAQ:

https://isocpp.org/wiki/faq/references#returning-refs

这篇关于函数何时必须在c ++中返回引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆