一、引用基本语法
1.1基本引用
int a=10;
int & b=a; //引用->作用就是给一个内存空间 起别名
语法:类型 & 别名 = 原名
void test01()
{
int a=10;
int & b=a; // a和b指向同一块内存地址
b=20; //修改地址的值
cout<<"a = "<<a<<endl; //值a=20;
}
1.2引用必须要初始化
void test02()
{
int &b;//不允许
int a=10;
int & b=a;
//一旦初始化后 就不可以修改指向
int c=20;
b=c;//赋值
cout<<"a = "<<a<<endl;
cout<<"b = "<<b<<endl;
cout<<"c = "<<c<<endl;
}
1.3建立对数组的引用
void test03()
{
int arr[10];
int(&pArr)[10]=arr; //引用出一个新别名
for(itn i=0;i<10;i++)
{
arr[i]=i;
}
for(int i=0;i<10;i++)
{
cout<<pArr[i]<<endl; //使用别名打印输出
}
1.3.2先定义数组的类型,再定义引用
typedef int (ARRAY_TYPE)[10];
// 语法:类型 & 别名 = 原名
ARRAY_TYPE &pArr2=arr;
for(int i=0;i<10;i++)
{
cout<<pArr2[i]<<endl; //使用别名打印输出
}
}
二、参数的传递方式
2.1值传递
void myswap01(int a,int b)
{
int temp=a;
a=b;
b=temp;
cout<<"a = "<<a<<end;
cout<<"b = "<<b<<end;
//打印输出 a=20,b=10
}
void test01()
{
int a=10;
int b=20;
myswap01(a,b);
cout<<"a = "<<a<<end;
cout<<"b = "<<b<<end;
//打印输出 a=10,b=20
}
2.2地址传递
void myswap02(int * a,int * b)
{
int temp=*a;
*a=*b;
*b=temp;
}
void test02()
{
int a=10;
int b=20;
myswap01(a,b);
cout<<"a = "<<a<<end;
cout<<"b = "<<b<<end;
//打印输出 a=20,b=10 传递地址 修改本体
}
2.3 引用传递
void myswap03(int & a,int & b)//int & a=a;int & b=b;
{
int temp=a;
a=b;
b=temp;
}
void test03()
{
int a=10;
int b=20;
myswap01(a,b);
cout<<"a = "<<a<<end;
cout<<"b = "<<b<<end;
//打印输出 a=20,b=10 引用传递 修改成功
}
三、引用注意事项
3.1不要返回局部变量的引用
int & myFunc()
{
int a=10; //局部变量a 执行完myFunc()后 将会被释放掉,
return a; //编译器寻找时使用非法内存
}
void test01()
{
int & ret=myFunc();
cout<<"ret = "<<ret<<endl;//编译器优化结果,保存之前的数据ret=10;
cout<<"ret = "<<ret<<endl;
cout<<"ret = "<<ret<<endl;//ret=?
/*多运行几次结果后,显示乱码。*/
}
3.2 如果函数返回值是一个引用,那么这个函数可以作为左值进行运算
int & myFunc2()
{
static int a=10; //提高生命周期
return a;
}
void test02()
{
int & ret=myFunc();
cout<<"ret = "<<ret<<endl;//始终ret=10
myFunc2()=100;
cout<<"ret = "<<ret<<endl;//ret=100
}
四、指针引用
4.1 引用的本质在C++内部是一个指针常量,所以必须初始化
Type & ref=val; //Type* const ref =&val;
void testFunc(int & ref)
{
ref=100;//ref是引用,转换为*ref=100
}
struct Person
{
int age;
};
void allocateSpace(Person **p) //**p 指向Person本体 *p指针 p指针的指针
{
*p=(Person *)malloc(sizeof(Person));
(*p)->age=100;
}
void test01()
{
Person * p=NULL;
allocateSpace(&p);
cout<<" 年龄: "<<p->age<<endl;
}
4.2指针的引用
struct Person
{
int age;
};
void allocateSpace(Person* &p) //Person * &p=p
{
p=(Person *)malloc(sizeof(Person));
p->age=200;
}
void test01()
{
Person * p=NULL;
allocateSpace(p);
cout<<" 年龄: "<<p->age<<endl;
}
五、常量的引用
int & ref=10; //引用必须引一块合法的空间
const int & ref=10//但是加入const之后,语法通过,编译器优化类似于 int temp=10;const int & ref=temp;
5.2常量引用 使用场景 修饰函数中的形参 防止误操作
void showValue(int a) //值传递 拷贝临时数据内存
void showValue(int &a) //引用 没有拷贝临时数据内存 节省空间
void showValue(const int &a)//防止误操作 在局部中修改掉引用原址的值 加上const不可修改
{
a=10000; //不加const 修改a值成功 加上const 程序报错
cout<<a<<endl;
}
void test01()
{
int a=100;
showValue(a);
}