天天看点

C++入门day07(引用)引用

[今日调侃:网友说,Python适合不想当程序员的人用来编程]

引用

引用的基本使用

作用:给变量起别名

语法:

注意:

引用必须初始化,而且不可改变

引用做函数参数

作用:函数传参时,可以利用引用的技术让形参修饰实参

优点:可以简化指针修改实参

引用传递(&)和地址传递(*)的效果是一样的

引用做函数返回值

作用:引用是可以作为函数的返回值存在的

注意:不要返回局部变量的引用

用法:函数调用作为左值

#include <iostream>
using namespace std;

// 引用传递 
void swap(int &a,int&b)
{
	int temp = a;
	a = b;
	b = temp;
}

// 引用做返回值
int& test01()
{
	int a = 10;
	return a;
} 

int& test02()
{
	static int a = 10010;
	return a;
} 

int main()
{
	int a = 10;
	int &b = a;
	cout<<"--a = "<<a<<endl;
	cout<<"--b = "<<b<<endl;
	b = 20;
	cout<<"a = "<<a<<endl;
	cout<<"b = "<<b<<endl;
	
	// 引用传递  
	int x = 11;
	int y = 22;
	swap(x,y);
	cout<<"x = "<<x<<endl;
	cout<<"y = "<<y<<endl;
	
	// 引用做函数的返回值 
	int &ref = test01();
	cout<<"ref ="<<ref<<endl;  // 第一次正确,编译器干的 
	cout<<"ref ="<<ref<<endl;  // 第二次就乱码了
	 
	int &ret = test02();
	cout<<"ret ="<<ret<<endl;  
	cout<<"ret ="<<ret<<endl;  
	
	// 左值
	test02() = 10086;
	cout<<"ret ="<<ret<<endl;
	
	system("pause");
	return 0;
}
           

运行结果:

--a = 10
--b = 10
a = 20
b = 20
x = 22
y = 11
ref =10
ref =0
ret =10010
ret =10010
ret =10086
请按任意键继续. . .
           

引用的本质

本质:引用的本质在 C++ 内部实现是一个指针常量

常量引用

作用:常量引用主要用来修饰形参,防止误操作

在函数形参列表中,可以加 const 修饰形参,防止形参改变实参

#include <iostream>
using namespace std;

// 引用的本质 

// 发现是引用,转换为 int * const ref = &a;
void func(int& ref)
{
	ref = 100;  // ref 是引用,转换为 * ref = 100 
} 

void showValue(const int &val)
{
	cout<<"val = "<<val<<endl;
}


int main()
{
	int a = 10;
	// 自动转换为 int * const ref = &a;
	// 指针常量是 指针指向不可改, 也说明为什么引用不可更改
	int& ref = a;
	ref = 20;  // 内部发现 ref 是引用,自动帮我们转换为: *ref = 20; 
	
	cout<<"a: "<<a<<endl;
	cout<<"ref: "<<ref<<endl;
	
	func(a);
	cout<<"a: "<<a<<endl;
	cout<<"ref: "<<ref<<endl;
	
	// 常量引用
	// 加上 const 之后,编译器将代码修改了,编译器搞得临时值 
	// int temp = 10; const int & ref = temp;
	// const int & ref02 = 10;     // 这是可以的 
	
	int k = 100;
	showValue(k);
	
	system("pause");
	return 0;
}
           

运行结果:

a: 20
ref: 20
a: 100
ref: 100
val = 100
请按任意键继续. . .
           

继续阅读