第一周学习:引用

概念
  1. 定义引用一定要将其initialize成某个变量
  2. 引用一旦绑定后,就不会再引用别的变量
  3. 引用只能是变量,不能是常量或表达式
 	double a=4,b=5;
	double& r1=a;
	double& r2=r1;
	r2=10;
	cout<<a<<endl;
	r1=b;
	cout<<a<<endl;

输出结果10 5

应用

交换两个数据的值swap()

	void swap1(int r1,int r2);
	void swap2(int& r1,int& r2);
	void swap3(int* r1,int* r2);

	int r1=10,r2=50;
	swap1(r1,r2);
	cout<<"r1: "<<r1<<"\tr2: "<<r2<<endl;
	swap2(r1,r2);
	cout<<"r1: "<<r1<<"\tr2: "<<r2<<endl;
	swap3(&r1,&r2);
	cout<<"r1: "<<r1<<"\tr2: "<<r2<<endl;

输出结果

r1: 10  r2: 50
r1: 50  r2: 10
r1: 10  r2: 50

作为函数的返回值

常引用

const int& r = n
不能通过常引用去修改其引用内容

const T&的类型的常变量和类型的引用不能用来初始化T &类型的引用,因为如果可以的话,那就可以修改const类型引用了。

猜你喜欢

转载自blog.csdn.net/ZmJ6666/article/details/108545791