从C到C++:“引用”的概念和应用

引用的概念

举例:

#include<iostream>
using namespace std;

int main() 
{
	int n = 7;
	int & r = n;
	r = 4;
	cout << r << endl;
	cout << n << endl;
	n = 5;
	cout << r << endl;

}

输出

4
4
5

注意事项:

举例:

引用的简单示例

交换两个整型变量值

#include<iostream>
using namespace std;
void swap(int & a, int & b)//引用,不需要取地址
{
	int tmp;
	tmp = a;
	a = b;
	b = tmp;
}
int main() 
{
	int n1 = 2, n2 = 3;
	swap(n1,n2);
	cout << n1 <<"  "<< n2;
}

引用作为函数的返回值

#include<iostream>
using namespace std;

int n = 4;
int & SetValue() { return n; } //返回值为一个整型的引用,引用了n

int main() 
{
	SetValue() = 40;//对函数调用的结果进行赋值,等价于对n进行复制
	cout << n << endl; //n=40
	return 0;
}

常引用

定义引用时,在前面加const关键字

int n;
const int & r = n; // r的类型为const int &

特点:不能通过常引用修改其引用的内容

#include<iostream>
using namespace std;
int main() 
{
	int n = 100;
	const int & r = n;
	n = 300;
	cout << "r=" << r << endl; //300
	cout << "n=" << n << endl; //300
}

常引用和非常引用类型的转化

原文地址:https://www.cnblogs.com/rookieveteran/p/13803317.html