引用
在C++中引用相当于给变量起一个别名
语法
数据类型 &别名 = 变量;
#include <iostream>
#include <cstdlib>
using namespace std;
void test01()
{
int a = 10;
int &b = a;
b = 100;
cout << "a = " << a << endl << "b = " << b << endl;
}
// 注意事项
void test02()
{
// 引用必须初始化
int a = 10;
// int &b; // error:必须初始化
int &b = a;
// 引用一旦初始化后,就不可以指向别的位置
}
int main()
{
test01();
return EXIT_SUCCESS;
}
a = 100
b = 100
对数组的引用
#include <iostream>
#include <cstdlib>
using namespace std;
void test01()
{
// 直接建立引用
int arr[5] = {1,2,3,4,5};
int (&pARR)[5] = arr;
for (size_t i = 0; i < 5; ++i)
{
cout << pARR[i] << endl;
}
// 先定义数组类型,再引用
typedef int (ARRAY_TYPE)[5];
ARRAY_TYPE &pARR2 = arr;
for (size_t i = 0; i < 5; ++i)
{
cout << pARR2[i] << endl;
}
// 先定义数组引用的类型,再引用
typedef int (&ARRAY_TYPE_REF)[5];
ARRAY_TYPE_REF pARR3 = arr;
for (size_t i = 0; i < 5; ++i)
{
cout << pARR3[i] << endl;
}
}
int main()
{
test01();
return EXIT_SUCCESS;
}
1
2
3
4
5
1
2
3
4
5
1
2
3
4
5
通过引用传参
#include <iostream>
#include <cstdlib>
using namespace std;
void test01(int &a, int &b)
{
int temp = a;
a = b;
b = temp;
}
int main()
{
int a = 1;
int b = 2;
test01(a,b);
cout << "a = " << a << endl << "b = " << b << endl;
return EXIT_SUCCESS;
}
a = 2
b = 1
引用可以简化指针
注意事项
-
引用必须引用合法的内存空间
-
不要返回局部变量的引用
引用的本质
引用本质上是一个指针常量
特殊引用
指针的引用
#include <iostream>
#include <cstdlib>
using namespace std;
struct Person
{
int age;
char name[4];
};
void createPerson(Person * &p)
{
p = (Person *)malloc(sizeof(Person));
p->age = 10;
}
void test01()
{
Person *person = NULL;
createPerson(person);
cout << "年龄:" << person -> age << endl;
free(person);
}
int main()
{
test01();
return EXIT_SUCCESS;
}
年龄:10
常量的引用
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
// int &b = 10 // 非法
const int &b = 10; // 编译器将代码修改为:int temp = 10; const int &b = temp;
cout << b << endl;
int *p = (int *)&b;
*p = 20;
cout << b << endl;
return EXIT_SUCCESS;
}
10
20
使用场景
// 加const修饰形参,为了防止误操作修改了值
void func(const int &a)
{
// TODO
}