黑马教程学习笔记——引用

1、引用的含义

//引用:取别名
//语法:数据类型 &别名=原名
#include  <iostream>
#include <string>
using namespace std;
int main()
{
	int a = 10;
	int &b = a;
	cout << a <<endl;//10
	cout << b << endl;//10

	b = 100;
	cout << a << endl;//100
	cout << b << endl;//100

	a = 60;
	cout << a << endl;//60
	cout << b << endl;//60
	
	system("pause");
	return 0;
}

2、引用注意事项

#include  <iostream>
#include <string>
using namespace std;
int main()
{
	int a = 10;
	//1、引用必须初始化
	//int &b; //错误,必须要初始化
	int &b = a;
	//2、引用在初始化后,不可以改变
	int c = 20;
	b = c;//赋值操作,而不是更改引用

	cout << a << endl;//20
	cout << b << endl;//20
	cout << c<< endl;//20
	system("pause");
	return 0;
}

3、引用做函数参数

//引用做函数参数
#include  <iostream>
#include <string>
using namespace std;
//1、值传递
void mySwap01(int a, int b)
{

	int temp = a;
	a = b;
	b = temp;
	//cout << a << endl;
	//cout << b << endl;
}
//2、地址传递
void mySwap02(int *a, int *b)
{

	int temp = *a;
	*a = *b;
	*b = temp;
	//cout << *a << endl;
	//cout << *b << endl;
}
//3、引用传递
void mySwap03(int &a, int &b)
{
	int temp = a;
	a = b;
	b = temp;
	cout << a << endl;
	cout << b << endl;
}
int main()
{
	int a = 10;
	int b = 20;
	//mySwap01(a, b);
	//mySwap02(&a,&b);
	mySwap03(a, b);
	cout << a << endl;
	cout << b << endl;

	system("pause");
	return 0;
}
//总结
//值传递:void mySwap01(int a, int b)  mySwap01(a, b);
//地址传递:void mySwap02(int *a, int *b)  mySwap02(&a,&b);
//引用传递:void mySwap03(int &a, int &b)  mySwap03(a, b);

4、引用做函数返回值

//引用做函数返回值
#include  <iostream>
#include <string>
using namespace std;
//引用做函数的返回值
//1、不要返回局部变量的引用
int & test01()
{
	int a = 10;//局部变量存放在四区中的 栈区
	return a;
}
//2、函数的调用可以作为左值
int & test02()
{
	static int a = 10;//静态变量,存放在全局区,全局区上的数据在程序结束后系统释放
	return a;
}

int main()
{
	//int &ref = test01();
	//cout << "ref=" << ref << endl;//10,编译器做了保留
	//cout << "ref=" << ref << endl;//显示地址,a的内存已经释放
	int &ref = test02();
	cout << "ref=" << ref << endl;//10
	cout << "ref=" << ref << endl;//10
	test02() = 1000;
	cout << "ref=" << ref << endl;//1000
	cout << "ref=" << ref << endl;//1000
	system("pause");
	return 0;
}

5、引用的本质

//发现是引用,转换为int* const ref =&a;
void func(int& ref)
{
	ref = 100;//ref是引用,转换*ref=100
	//引用的本质是一个指针常量,一旦初始化后,就不可以发生改变
}
int main()
{
	int a = 10;
	//自动转换为int* const ref =&a;指针常量是指针指向不可更改,也就说明引用为什么不能更改
	int &ref = a;
	ref = 20;//内部发现ref是引用,自动帮我们转换为*ref=20;

}

6、常量引用

#include  <iostream>
#include <string>
using namespace std;

void showValue(const int &val)
{
	//val = 1000;加const不可修改
	cout << "val=" << val << endl;
}
int main()
{
	//常量引用
	//使用场景;用来修饰形参,防止误操作
	//int a = 10;
	//加上const之后 编译器将代码修改 int temp=10;const int &ref=temp;
	//const int &ref = 10;//引用必须引一块合法的内存空间
	int a = 100;
	showValue(a);
	system("pause");
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值