博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[C++] Returning values by reference in C++
阅读量:5827 次
发布时间:2019-06-18

本文共 1736 字,大约阅读时间需要 5 分钟。

A C++ program can be made easier to read and maintain by using references rather than pointers. A C++ function can return a reference in a similar way as it returns a pointer.

When a function returns a reference, it returns an implicit pointer to its return value. This way, a function can be used on the left side of an assignment statement. For example, consider this simple program:

#include 
#include
using namespace std; double vals[] = {
10.1, 12.6, 33.1, 24.1, 50.0}; double& setValues( int i ){ return vals[i]; // return a reference to the ith element} // main function to call above defined function.int main (){ cout << "Value before change" << endl; for ( int i = 0; i < 5; i++ ) { cout << "vals[" << i << "] = "; cout << vals[i] << endl; } setValues(1) = 20.23; // change 2nd element setValues(3) = 70.8; // change 4th element cout << "Value after change" << endl; for ( int i = 0; i < 5; i++ ) { cout << "vals[" << i << "] = "; cout << vals[i] << endl; } return 0;}

 

 

When the above code is compiled together and executed, it produces the following result:

Value before changevals[0] = 10.1vals[1] = 12.6vals[2] = 33.1vals[3] = 24.1vals[4] = 50Value after changevals[0] = 10.1vals[1] = 20.23vals[2] = 33.1vals[3] = 70.8vals[4] = 50

 

When returning a reference, be careful that the object being referred to does not go out of scope. So it is not legal to return a reference to local var. But you can always return a reference on a static variable.

int& func() {   int q;   //! return q; // Compile time error   static int x;   return x;     // Safe, x lives outside this scope}

 

转载于:https://www.cnblogs.com/tianhangzhang/p/4983694.html

你可能感兴趣的文章
jquery 选择器
查看>>
转://Oracle not in查不到应有的结果(NULL、IN、EXISTS详解)
查看>>
listbox用法
查看>>
冲刺第九天 1.10 THU
查看>>
一个不错的Node.js进阶学习引导
查看>>
《团队-科学计算器-项目总结》
查看>>
pythoy的configparser模块
查看>>
传值方式:ajax技术和普通传值方式
查看>>
Linux-网络连接-(VMware与CentOS)
查看>>
经典的CSS代码(转)
查看>>
Django
查看>>
MIPS中的异常处理和系统调用【转】
查看>>
Linux系统调用、新增系统调用方法【转】
查看>>
寻找链表相交节点
查看>>
jquery对象 与 document 对象的互为转换关系
查看>>
LeetCode OJ:Path Sum II(路径和II)
查看>>
Python 核心编程(第二版)——函数和函数式编程
查看>>
AS3——禁止swf缩放
查看>>
说给部分程序员听
查看>>
linq 学习笔记之 Linq基本子句
查看>>