2023-3-2首次编辑
2023-3-7第一次修改(增加目录)
Unit 2:引用
一.引用概述
- 和C语言的指针一样,并且使语法更加简洁
- 给空间取别名
语法:
#define _CRT_SECIRE_NO_WARNINGS
#include <iostream>
using namespace std;
void test(int &a)//int &a = a;
{
a = 200;
}
int main()
{
int a = 10;
test(a);
cout << "a:" << a << endl;
system("pause");
return 0;
}
注意:
- 引用创建时,必须初始化 [int& a; //err]
- 引用一旦创建不能改变它的指向
- 必须引用一块合法的空间
二.引用的本质
#define _CRT_SECIRE_NO_WARNINGS
#include <iostream>
using namespace std;
//引用的本质:编译器在内部使用常指针来实现
//发现是引用,转换为int* const ref = &a;
void test(int &ref) {
ref = 100;
}
int main()
{
int a = 10;
int &aRef = a;
//自动转换为int* const aRef = &a;
//说明:引用必须初始化
aRef = 20;
//发现内部是引用,自动转换成:*aRef = 20;
cout << "a:" << a << endl;
cout << "aRef:" << aRef << endl;
test(a);
cout << "a:" << a << endl;
system("pause");
return 0;
}
三.数组的引用
#define _CRT_SECIRE_NO_WARNINGS
#include <iostream>
using namespace std;
int main()
{
int arr[] = { 1, 2, 3, 4, 5 };
//第一种方法(常用)
//1.定义数组类型
typedef int(MY_ARR1)[5];
//2.建立引用
MY_ARR1 &arref1 = arr; //int& a = b;
//第二种方法(常用)
//直接定义引用
int(&arref2)[5] = arr;
//第三种方法
//建立引用数组类型
typedef int(&MY_ARR2)[5];
MY_ARR2 arref3 = arr;
for (int i = 0; i < 5; i++)
{
cout << arref1[i];
}
cout << endl;
for (int i = 0; i < 5; i++)
{
cout << arref2[i];
}
cout << endl;
for (int i = 0; i < 5; i++)
{
cout << arref3[i];
}
cout << endl;
system("pause");
return 0;
}
四.指针的引用
#define _CRT_SECIRE_NO_WARNINGS
#include <iostream>
using namespace std;
void test1()
{
char* p = "翠花";
char* &q = p;
cout << q << endl;
}
//被调函数
void func(char* &tmp)//char* &tmp = mp;
{
char* p;
p = (char*)malloc(64);
memset(p, 0, 64);
strcpy(p, "小花");
tmp = p;
}
//主调函数
void test2()
{
char* mp = NULL;
func(mp);
cout << mp << endl;
}
int main()
{
test1();
test2();
system("pause");
return 0;
}
五.引用的使用场景
#define _CRT_SECIRE_NO_WARNINGS
#include <iostream>
using namespace std;
//1.引用作为函数参数
void func1(int &a, int &b)
{
int sum = a + b;
cout << "sum=" << sum << endl;
}
void test1()
{
int a = 10;
int b = 20;
func1(a, b);
}
//2.引用作为函数的返回值
int &func2()
{
//注意1:不要返回局部变量的引用
static int a = 10;
return a;
}
void test2()
{
int &q = func2();
cout << "q:" << q << endl;
cout << "func2:" << func2() << endl;
//注意2:如果要函数当左值,那么该函数必须返回引用
func2() = 100;
cout << "func2:" << func2() << endl;
}
int main()
{
test1();
test2();
system("pause");
return 0;
}
六.常量引用
#define _CRT_SECIRE_NO_WARNINGS
#include <iostream>
using namespace std;
int main()
{
//int &ref1 = 10;
//err:
//非常量引用的初始值必须为左值
const int &ref2 = 10;
//ok:
//int tmp = 10;
//const int &ref2 = tmp;
system("pause");
return 0;
}