用途 给变量起别名
语法 数据类型 &别名 = 原名
注意 新建引用必须初始化 引用不可更改指向
本质 本质上就是一个指针常量 int * const p = &a;
#include <iostream>
using namespace std;
int main()
{
int a = 10;
int& b = a;
cout << a << " " << b << endl;
return 0;
}
引用做函数形参的小例子
#include <iostream>
using namespace std;
void swap(int a,int b)
{
int temp = a;
a = b;
b = temp;
}
//指针的方式交换
void swap01(int* a, int* b)
{
int temp = *a;
*a = *b;
*b = temp;
}
//引用的方式交换
void swap02(int& a, int& b)
{
int temp = a;
a = b;
b = temp;
}
int main()
{
int a = 10;
int b = 20;
swap(a, b);
cout << "a:" << a << "b:" << b << endl;
swap01(&a, &b);
cout << "a:" << a << "b:" << b << endl;
swap02(a, b);
cout << "a:" << a << "b:" << b << endl;
return 0;
}
注意 不可以利用函数直接返回局部变量的引用
可以利用函数返回常量的引用
返回值为引用的函数可以作为被赋值的一方使用
#include <iostream>
using namespace std;
int& run()
{
static int a = 10;
return a;
}
int main()
{
int& p = run();
cout << p << endl;
cout << p << endl;
run() = 100;
cout << p << endl;
cout << p << endl;
return 0;
}
使用const关键字修饰形参防止误操作
void run2(const int& a)
{
}
指向指针的引用
函数形参为数组
#include <stdlib.h>
#include <string.h>
#pragma warning(disable:4996)
//二级指针接受一级指针
void writeStr(char ** str) {
*str = (char *)calloc(1,23);
strcpy(*str,"hello word");
return;
}
//引用的写法
void writeStr2(char* &str) {
str = (char*)calloc(1, 23);
strcpy(str, "hello word 1");
return;
}
void test01() {
char* godv = NULL;
writeStr2(godv);
cout << godv << endl;
free(godv);
}
int main()
{
test01();
}