c++中的引用

目录

一、引用的概念

二、引用的本质

三、指针的引用

四、常量引用


一、引用的概念

引用(reference)就是C++对C语言的重要扩充。引用就是某一变量(目标)的一个别名,对引用的操作与对变量直接操作完全一样。

原类型名&别名 = 旧名

int a = 10;

​int &b = a;//b就是a的别名 b和a有相同的地址

b = 100;

//引用一旦初始化之后不能改变引用的指向

代码示例

#include <iostream>
#include <stdlib.h>

using namespace std;

void test01()
{
    int a = 10;
    int &b = a;
    b = 100;
    cout << a << endl;//输出100
}

int main()
{
    test01();
    return 0;
}

&在等号左边是起标识作用 在右边是求地址运算

引用定义时必须初始化

不能引用NULL

函数传参中的引用:代码示例

#include <iostream>
#include <stdlib.h>

using namespace std;

void get_met(int *(&q))//int * &q = p;
{
    q = (int *)malloc(5 * sizeof(int));
}

void swap(int &x,int &y)//相当于 int &x = a;
{
    int tmp = x;
    x = y;
    y = tmp;
}

void test01()
{
    int a = 10;
    int b = 20;
    swap(a,b);
    cout << a <<" "<< b <<endl;
}

void test02()
{
    int *p = NULL;
    get_met(p);
}

int main()
{
    test01();
    return 0;
}

不能返回局部变量的引用 可以返回静态变量(static)的引用 静态变量不会被释放

二、引用的本质

引用的本质是在c++内部实现是一个指针常量

type &b = a; //type * const b = &a;

#include <iostream>
#include <stdlib.h>

using namespace std;

void test01()
{   
    int a = 10;
    int &b = a;//编译器 int * const b = &a;
}

void fun(int *&q)//int *&q = p;编译器 int * const q = &p; 
{

}

void test02()
{   
    int *p = NULL;
    fun(p);
}

int main()
{
    test01();
    return 0;
}

三、指针的引用

type * &q = p; //type * const q = &p;

#include <iostream>
#include <stdlib.h>

using namespace std;

void fun(int *&q)//int *&q = p;编译器 int * const q = &p; 
{

}

void test02()
{   
    int *p = NULL;
    fun(p);
}

int main()
{
    test02();
    return 0;
}

四、常量引用

常量引用定义格式:

const type& ref = val;(const 修饰&)

#include <iostream>
#include <stdlib.h>

using namespace std;

void test01()
{
    int a = 10;
    //const修饰的是引用 不能通过引用去修改引用的这块空间
    const int &b = a;
    //b = 100;//错误
}

void test02()
{
    //int &b = 100;//不能引用常量 常量不是地址
    const int &b = 1;//tmp = 1; const int &b = tmp;
}

int main()
{
    test01();
    test02();
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值