When a variable is declared as reference, it becomes an alternative name for an existing variable. A variable can be declared as reference by putting ‘&’ in the declaration.

 1 #include<iostream>
2 using namespace std;
3
4 int main()
5 {
6 int x = 10;
7
8 // ref is a reference to x.
9 int& ref = x;
10
11 // Value of x is now changed to 20
12 ref = 20;
13 cout << "x = " << x << endl ;
14
15 // Value of x is now changed to 30
16 x = 30;
17 cout << "ref = " << ref << endl ;
18
19 return 0;
20 }
21
22
23   Output:
25   x = 20
26   ref = 30

  Following is one more example that uses references to swap two variables.

 1 #include<iostream>
2 using namespace std;
3
4 void swap (int& first, int& second)
5 {
6 int temp = first;
7 first = second;
8 second = temp;
9 }
10
11 int main()
12 {
13 int a = 2, b = 3;
14 swap( a, b );
15 cout << a << " " << b;
16 return 0;
17 }
18
19
20 Output: 3 2

  References  vs Pointers

  Both references and pointers can be used to change local variables of one function inside another function. Both of them can also be used to save copying of big objects when passed as arguments to functions or returned from functions, to get efficiency gain.
  Despite above similarities, there are following differences between references and pointers.

  References are less powerful than pointers
  1)Once a reference is created, it cannot be later made to reference another object; it cannot be reseated. This is often done with pointers.
  2)References cannot be NULL. Pointers are often made NULL to indicate that they are not pointing to any valid thing.
  3)A reference must be initialized when declared. There is no such restriction with pointers

  Due to the above limitations, references in C++ cannot be used for implementing data structures like Linked List, Tree, etc. In Java, references don’t have above restrictions, and can be used to implement all data structures. References being more powerful in Java, is the main reason Java doesn’t need pointers.

  上面的不同点可以总结为如下几条:

  (1)引用始终与某个对象相关联的,因此引用在定义时必须进行初始化,而指针在定义时则可以不初始化;

  (2)引用在定义后不能进行更改,而指针在定义后则可以更改,指向其他对象;

  (3)赋值行为的差异:对引用赋值修改的是引用所关联对象的值,对指针赋值则修改的是指针本身的值;

  (4)引用不能为NULL,而指针可以为NULL,因此,在编程的时候,引用的效率可能会比较高,因为不需要进行NULL判断。

  References are safer and easier to use:
  1) Safer: Since references must be initialized, wild references like wild pointers are unlikely to exist. It is still possible to have references that don’t refer to a valid location (See questions 5 and 6 in the below exercise )
  2) Easier to use: References don’t need dereferencing operator to access the value. They can be used like normal variables. '&' operator is needed only at the time of declaration. Also, members of an object reference can be accessed with dot operator ('.'), unlike pointers where arrow operator (->) is needed to access members.

  

  Together with the above reasons, there are few places like copy constructor argument where pointer cannot be used.

  Reference must be used pass the argument in copy constructor. Similarly references must be used for overloading some operators like ++.

Exercise:
  Predict the output of following programs. If there are compilation errors, then fix them.

  Question 1

 1 #include<iostream>
2 using namespace std;
3
4 int &fun()
5 {
6 static int x = 10;
7 return x;
8 }
9 int main()
10 {
11 fun() = 30;
12 cout << fun();
13 return 0;
14 }

  Output:  30

  

  Question 2

 1 #include<iostream>
2 using namespace std;
3
4 int fun(int &x)
5 {
6 return x;
7 }
8 int main()
9 {
10 cout << fun(10);
11 return 0;
12 }

  编译错误:cannot convert parameter 1 from 'const int' to 'int &'

  原因:fun函数的参数是non-const引用,而10字面值可以作为实参传递给const &,而不可以传递给&。

  Question 3

 1 #include<iostream>
2 using namespace std;
3
4 void swap(char * &str1, char * &str2)
5 {
6 char *temp = str1;
7 str1 = str2;
8 str2 = temp;
9 }
10
11 int main()
12 {
13 char *str1 = "GEEKS";
14 char *str2 = "FOR GEEKS";
15 swap(str1, str2);
16 cout<<"str1 is "<<str1<<endl;
17 cout<<"str2 is "<<str2<<endl;
18 return 0;
19 }

  Output:
  str1 is FOR GEEK
  str2 is GEEKS

  Question 4

1 #include<iostream>
2 using namespace std;
3
4 int main()
5 {
6 int x = 10;
7 int *ptr = &x;
8 int &*ptr1 = ptr;
9 }

  编译错误。将第8行代码改为int *&ptr1 = ptr; *&ptr1才是指针的引用。

  Question 5

1 #include<iostream>
2 using namespace std;
3
4 int main()
5 {
6 int *ptr = NULL;
7 int &ref = *ptr;
8 cout << ref;
9 }

  程序崩溃。因为没有NULL引用。

  Question 6

 1 #include<iostream>
2 using namespace std;
3
4 int &fun()
5 {
6 int x = 10;
7 return x;
8 }
9 int main()
10 {
11 fun() = 30;
12 cout << fun();
13 return 0;
14 }

  Output:10

  注意该题的运行结果与Question 1运行结果不同原因。

  题目解释如下:

  question 4: you can't have a pointer to a reference because a pointer must point to an object and a reference itself is not an object, but an alias to another object. but you can have a reference to a pointer. int *&ptr1=ptr is legal - it means that ptr1 is a reference (alias) for the int pointer ptr.

  question 5: the reference isn't technically NULL. it is referencing an actual object. however, that object is a pointer that is pointing to NULL.

  question 6: a temporary object is created for the return type so that it can be printed by cout, after the line is executed, the temporary variable is destroyed.

  

  Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

  转载请注明:http://www.cnblogs.com/iloveyouforever/

  2013-11-25  21:05:21

References in C++的更多相关文章

  1. Oracle Created Database Users: Password, Usage and Files References (文档 ID 160861.1)

    This document is no longer actively maintained, for info on specific (new) users in recent product e ...

  2. Atitit java方法引用(Method References) 与c#委托与脚本语言js的函数指针

    Atitit java方法引用(Method References) 与c#委托与脚本语言js的函数指针   1.1. java方法引用(Method References) 与c#委托与脚本语言js ...

  3. object references an unsaved transient instance - save the transient instance before flushing错误

    异常1:not-null property references a null or transient value解决方法:将“一对多”关系中的“一”方,not-null设置为false(参考资料: ...

  4. C++ 之 const references

    extraction from The C++ Programming Language 4th. ed., Section 7.7 References, Bjarne Stroustrup To ...

  5. Notice: Only variable references should be returned by reference(PHP版本兼容性问题)

    摘自:http://sushener.spaces.live.com/blog/cns!BB54050A5CFAFCDD!435.entry PHP5一个很让人恼火的一点就是BC(向后兼容)不是很理想 ...

  6. [翻译]Understanding Weak References(理解弱引用)

    原文 Understanding Weak References Posted by enicholas on May 4, 2006 at 5:06 PM PDT 译文 我面试的这几个人怎么这么渣啊 ...

  7. ManyToMany【项目随笔】关于异常object references an unsaved transient instance

    在保存ManyToMany  时出现异常: org.springframework.dao.InvalidDataAccessApiUsageException: org.hibernate.Tran ...

  8. Solve: Your project references the latest version of Entity Framework (for MySQL) in Visual Studio 2013

    The error message while trying to create a ADO.net Entity Data Model ( Entity Framework 6 ) for MySq ...

  9. 【翻译】C# Tips & Tricks: Weak References - When and How to Use Them

    原文:C# Tips & Tricks: Weak References - When and How to Use Them Sometimes you have an object whi ...

  10. Effective Java 06 Eliminate obsolete object references

    NOTE Nulling out object references should be the exception rather than the norm. Another common sour ...

随机推荐

  1. C++ IO基础

    一:c++I/O处理,按照数据输入输出的过程,形象的将其看做流.数据在流中进行传播. 所有的流有两个基类:ios和streambuf类 streambuf:提供对缓冲区的基本操作,设置缓冲区等 ios ...

  2. Python MySSH 实现剧本执行器

    通过封装Paramiko这个SSH模块,我们可以实现远程批量管理Linux主机,在上一篇文章中我们封装过一个MySSH类,这个类可以执行命令上传下载文件等,我们在这个类的基础上,实现一个简单的任务执行 ...

  3. eclipse查看jar包源代码

    方法一:将jd-gui集成在Eclipse中 https://jingyan.baidu.com/article/b24f6c8275536686bfe5daed.html    下载2个反编译文件, ...

  4. [bzoj1711]吃饭

    由于无法直接将果汁和饮料连边,所以将人放在中间,果汁和饮料放在两侧,然后分别向对应的人连边.同时,为了保证每一个人只被算一次,对每一个人裂点,两个点中间连一条流量为1的边. 1 #include< ...

  5. [luogu7116]微信步数

    先判定无解,当且仅当存在一个位置使得移动$n$步后没有结束且仍在原地 暴力枚举移动的步数,记$S_{i}$为移动$i$步(后)未离开范围的点个数,则恰好移动$i$步的人数为$S_{i-1}-S_{i} ...

  6. Vue: 一个简单的Vue2.0 v-model双向数据绑定的实现,含源代码,小白也能看懂

    首先说一下原理吧 View层(dom元素)的变动如何响应到Model层(Js变量)呢? 通过监听元素的input事件来动态的改变js变量的值,实际上不是改变的js变量的值,而是改变的js变量的gett ...

  7. 服务API版本控制设计与实践

    一.前言 笔者曾负责vivo应用商店服务器开发,有幸见证应用商店从百万日活到几千万日活的发展历程.应用商店客户端经历了大大小小上百个版本迭代后,服务端也在架构上完成了单体到服务集群.微服务升级. 下面 ...

  8. Codeforces 582D - Number of Binominal Coefficients(Kummer 定理+数位 dp)

    Codeforces 题目传送门 & 洛谷题目传送门 一道数论与数位 dp 结合的神题 %%% 首先在做这道题之前你需要知道一个定理:对于质数 \(p\) 及 \(n,k\),最大的满足 \( ...

  9. BJ2 斜率限制器

    BJ2 斜率限制器 本文介绍斜率限制器取自于 Anastasiou 与 Chan (1997)[1]研究,其所利用的斜率限制器也是 Barth 与 Jespersen 限制器的一种修正形式,并且包含一 ...

  10. 【代谢组学】Metabolomics资源推送

    入门课程 伯明翰大学: Metabolomics: Understanding Metabolism in the 21st Century 数据处理 阿拉巴马大学伯明翰分校5年(2013-2018) ...