1. 引用的实质是取别名
原类型 &别名 = 旧名
2. 引用的用法
注意事项
2.1. 引用一旦初始化,不能更改引用的指向
2.2 引用定义时必须初始化
2.3 不能引用NULL
2.4 引用可以引用任意类型包括数组
2.5 &在等号的左边是引用,在等号的右边是取地址
3. 代码实现
#include <iostream>
using namespace std;
void test01()
{
int a = 10;
//引用一旦初始化不能改变引用的标识
int &b = a;
b = 100;
cout << "a=" << a << endl;
int c = 1;
//b = c; 代表把c赋值给b,不是给c取别名b
//int &b; 引用定义时必须初始化
}
void test02()
{
int arr[5] = {1, 2, 3, 4, 5};
int(&a)[5] = arr;
for (int i = 0; i < 5; i++)
{
cout << a[i] << " ";
}
cout << endl;
}
int main()
{
// test01();
test02();
return 0;
}
4. 函数的引用
4.1 引用可以作为函数的形参
4.2 不能返回局部变量的引用
代码实现
#include <iostream>
#include <cassert>
#include <cstdlib>
using namespace std;
void swap(int *pa, int *pb)
{
assert(pa && pb);
int tmp = *pa;
*pa = *pb;
*pb = tmp;
}
//int &x = a ; int &y = b;
void swap_ref(int &x, int &y)
{
int tmp = x;
x = y;
y = tmp;
}
void test01()
{
int a = 100;
int b = 200;
cout << "交换前:" << "a=" << a << " " << "b=" << b << endl;
swap(&a, &b);
cout << "交换后:" << "a=" << a << " " << "b=" << b << endl;
}
void test02()
{
int a = 100;
int b = 200;
cout << "交换前:" << "a=" << a << " " << "b=" << b << endl;
swap_ref(a, b);
cout << "交换后:" << "a=" << a << " " << "b=" << b << endl;
}
void get_mem(int **ppd)
{
*ppd = (int *) malloc(sizeof(int) * 5);
}
//int* (&ppd)= p
void get_mem_ref(int* &ppd)
{
ppd = (int *) malloc(sizeof(int) * 5);
}
void test03()
{
int *p = NULL;
//get_mem(&p);
get_mem_ref(p);
}
//返回引用
int& test04()
{
//能不能返回一个变量的引用,看这个变量是否被释放了
static int b =999;
int a= 10;
//return a; 不能返回局部变量的引用
return b;
}
int main()
{
//test01();
//引用交换
//test02();
//test03();
test04() = 1000;
return 0;
}
5.引用的本质
5.1 引用的本质是一个指针常量:type &b = a;
5.2 编译器底层这么实现的: type *const b = &a;
代码实现
void test01()
{
int a = 10;
int &b = a; //编译器优化 int* const b = &a
//指针常量 不能改变指针变量的指向
// b =0x100;
b = 1000;// *b =1000
}
void fun(int *&q) //int* &q = p ==> 编译器 int* const q =&p
{
}
void test02()
{
int *p = NULL;
fun(p);
}
6. 指针的引用
套用引用公式: type &q = p
type为指针类型
代码实现
void fun (int* &q) // int* &q = p
{
}
void test()
{
int *p=NULL;
fun(p);
}
7. 常量引用
7.1 const type &p = q;
7.2 常量引用代表不能通过引用去修改引用标识的那块空间
代码实现
void test01()
{
int a = 10;
// const修饰的是引用& 不能通过引用去修改引用的这块空间的内容
const int &b = a;
//b = 1000;//err
}
void test02()
{
//int &b = 100;//不能引用常量
const int &b = 1;//int tmp =1 ,const int &b= tmp
}