[zz]C++中的引用与指针

本文详细对比了C++中的引用与指针的区别,包括它们如何改变函数中的局部变量,提高大对象传递效率,以及引用在安全性与使用便捷性上的优势。同时指出引用在某些方面的局限性,如无法用于实现链表、树等数据结构。

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.

 

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.

引用与指针
两个引用和指针可以用来改变一个函数在另一个函数中的局部变量。两者也可以用来保存大对象的复制时作为参数传递给函数传递或者从函数返回,以获得效率增益。

 

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

 引用没有指针那么强大
1)引用一旦创建,它不能被以后作出引用另一对象,它不能被重新设置。而用指针可以。
2)引用不能为NULL。指针通常由NULL来表明他们没有指向任何有效的东西。
3)声明引用时必须被初始化。指针没有这样的限制

 

references in C++ cannot be used for implementing data structures like Linked List, Tree, etc.

C++中的引用不能用来实现像链表,树等数据结构。

 

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.

 

Reference must be used pass the argument in copy constructor and some operators overloading.

 

 

转载于:https://www.cnblogs.com/zzzsun/p/3446613.html

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值