引用
引用基础
#include<iostream>
using namespace std;
/*
1、引用的基本语法
引用:给一段内存空间起别名
语法:类型 & 别名 = 原名
*/
void test1()
{
int a = 10;
int &b = a;
b = 20;
cout << "a = " << a << endl;
}
/*
注意:
1、引用必须要初始化
*/
void test2()
{
int a = 10;
// int &b;
int &b = a; // 引用一旦初始化就不能修改它的指向了
int c = 20;
b = c; // 相当于赋值操作
cout << "a = " << a << endl;
cout << "b = " << b << endl;
cout << "c = " << c << endl;
}
/*
2、建立一个对数组的引用
(1)、先定义出数组的类型,在定义引用
数组类型定义:typedef int(Array)[10];
Array arr;
Array &pArray2 = arr;
(2)、
int arr[10];
int(&parr)[10] = arr;
*/
void test3()
{
int arr[10];
int(&parr)[10] = arr;
int i;
for ( i = 0; i < 10; i++)
{
arr[i] = i + 1;
}
for (i = 0; i < 10; i++)
{
cout << parr[i] << endl;
}
}
int main()
{
// test1();
// test2();
test3();
system("pause");
return 0;
}
函数中的引用
#include<iostream>
using namespace std;
// 1、值传递
void myswap01(int a, int b)
{
int t = a;
a = b;
b = t;
}
// 2、地址传递
void myswap02(int *a,int *b)
{
int t = *a;
*a = *b;
*b = t;
}
// 3、引用传递
void myswap03(int &a, int &b)
{
int temp = a;
a = b;
b = temp;
}
void test1()
{
int a = 10;
int b = 20;
// myswap01(a, b);
// myswap02(&a, &b);
// myswap03(a, b);
cout << "a = " << a << endl;
cout << "b = " << b << endl;
}
/*
引用的注意事项
1、不要返回局部变量的引用
*/
int &myf()
{
int a = 10;
return a;
}
// 2、如果函数的返回值是一个引用,那么这个函数可以作为左值进行运算
int &myf02()
{
static int a = 10; // static 这块内存并没有被释放掉
return a;
}
void test02()
{
// int &result = myf();
int &result = myf02();
cout << "result = " << result << endl;
cout << "result = " << result << endl;
cout << "result = " << result << endl;
cout << "result = " << result << endl;
myf02() = 100;
cout << "result = " << result << endl;
}
int main()
{
// test1(); //参数的传递方式
// test02(); //引用的注意事项
system("pause");
return 0;
}
引用的本质
引用的本质在C++内部是一个指针常量
#include<iostream>
using namespace std;
void f(int &p) // 编译器发现是引用,自动转换成 int * const p = &a;
{
p = 30; // *p = 30;
}
void test01()
{
int a = 10;
int& p = a; // 自动转换成 int * const p = &a; 引用的本质是一个常量指针
// 回答了引用为什么必须要初始化 为什么引用一旦初始化后就不能修改它的指向
p = 20;// 编译器内部发现是引用,自动帮我们转换为:*p = 20;
cout << "a = " << a << endl;
cout << "p = " << p << endl;
f(a);
}
int main()
{
test01();
system("pause");
return 0;
}
指针的引用
#include<iostream>
using namespace std;
struct Teacher
{
int age;
};
void f01(Teacher ** p)
{
(*p) = (Teacher *)malloc(sizeof(Teacher));
}
void test01()
{
Teacher * p = NULL;
f01(&p);
p->age = 100;
cout << "p->age = " << p->age << endl;
}
// 2、指针的引用
void f02(Teacher* &p)
{
p = (Teacher *)malloc(sizeof(Teacher));
}
void test02()
{
Teacher *p = NULL;
f02(p);
p->age = 100;
cout << "p->age = " << p->age << endl;
}
int main()
{
// test01();
test02();
system("pause");
return 0;
}
常量的引用
#include<iostream>
using namespace std;
void test01()
{
// int &p = 10; // 引用必须引用一段合法的内存空间
const int &p = 10; // 编译器优化 类似于:int t = 10; const int &t = temp;
}
// 2、常量引用应用场景
void print_a(const int &a)
{
// a = 100 const 防止误操作
cout << "a = " << a << endl;
}
void test02()
{
int a = 10;
print_a(a);
}
int main()
{
// test01();
test02();
system("pause");
return 0;
}