1.什么是引用?
引用是对变量取别名,操作别名等价于操作变量
2.有什么用途?
用于函数传参
3.使用
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
int data = 100;
int& quote = data;
cout<<"data ="<<data<<",quote="<<quote<<endl;
cout<<"&data="<<&data<<","e"<<"e<<endl;
//上述代码证明:别名的地址与值都和原变量相同
cout << "Hello World!" << endl;
return 0;
}
下为:用于函数传参的实际使用
#include <iostream>
using namespace std;
void setAddr01(int **q)//q = &p;
{
//*q == p
*q = (int *)calloc(1,sizeof(int));
}
void setAddr02(int* &q)//int* &q=p
{
//q==p
q = (int *)calloc(1,sizeof(int));
}
void test06()
{
int *p = NULL;
//setAddr01(&p);
setAddr02(p);
*p = 100;
cout<<"*p = "<<*p<<endl;
if(p != NULL)
{
free(p);
p=NULL;
}
}
int main(int argc, char *argv[])
{
test06();
cout << "Hello World!" << endl;
return 0;
}
常量引用:
#include <iostream>
using namespace std;
//引用作为函数的参数节省形参的空间开销
//函数内部不能 对ob赋值
void printData(const int &ob)
{
//ob=1000;//err
cout<<"ob = "<<ob<<endl;
}
void test08()
{
int data=100;
printData(data);
cout<<"data = "<<data<<endl;
}
int main(int argc, char *argv[])
{
test08();
cout << "Hello World!" << endl;
return 0;
}
4.本质
引用的本质是常量指针
int data = 10;
int& quote =data;//int *const quote = &data;
补充:
引用和指针的对比 | Value |
---|---|
1 | int* const ref = &a即本质是常量指针 |
2 | 引用创建的时候必须初始化,且不能为NULL |
3 | sizeof(引用) = 指向变量的大小;sizeof(指针)= 指针的大小 |
3 | 引用传递无需解引用 |