C++之引用

In the C++ programming language, a reference is a simple reference datatype that is less powerful but safer than the pointer type inherited from C. The name C++ reference may cause confusion, as in computer science a reference is a general concept datatype, with pointers and C++ references being specific reference datatype implementations. The definition of a reference in C++ is such that it does not need to exist. It can be implemented as a new name for an existing object (similar to rename keyword in Ada).

C++ references differ from pointers in several essential ways:

It is not possible to refer directly to a reference object after it is defined; any occurrence of its name refers directly to the object it references.

Once a reference is created, it cannot be later made to reference another object; it cannot be reseated. This is often done with pointers.

References cannot be null, whereas pointers can; every reference refers to some object, although it may or may not be valid. Note that for this reason, containers of references are not allowed.

References cannot be uninitialized. Because it is impossible to reinitialize a reference, they must be initialized as soon as they are created. In particular, local and global variables must be initialized where they are defined, and references which are data members of class instances must be initialized in the initializer list of the class's constructor. 

References can be thought of as "Symbolic links" in file system terminology. Symbolic links can be modified as though they were the file they were linked to and when a symbolic link is deleted the original file remains. Similarly, references can be deleted (whether by going out of scope or explicitly being removed if they were allocated in heap) and the original object that was referenced remains. Similarly, once a symbolic link has been created it can never be changed.

#include <iostream>
#include <stdlib.h>
using namespace std;

void fun(int &a, int &b);

int main(void)
{
	int x = 10;
	int y = 20;
	cout << x << "," << y << endl;
	fun(x, y);
	cout << x << "," << y << endl;
	system("pause");
	return 0;

}
void fun(int &a, int &b)
{
	int c = 0;
	c = a;
	a = b;
	b = c;
}

150429_WJKQ_2392809.png

程序利用引用实现了数据的互换。引用可以简单理解为是变量的一个别名,对别名的操作同样也会作用到原变量之上。

转载于:https://my.oschina.net/donngchao/blog/527318

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值