【2020.12.25】引用类型

引用类型

引用就是变量的别名

//基本类型
int x = 1;
int& p = x;
p = 2;
printf("%d\n", x);

//类
class MyClass
{
public:
    int x;
};

MyClass p;
MyClass& px = p;
px.x = 10;
printf("%d\n", p.x);

//指针
int* p = (int*)1;
int*& a = p;
a = (int*)2;
printf("%d\n", p);

//数组
int arr[] = {1, 2, 3};
int (&p)[3] = arr;
p[0] = 4;
printf("%d\n", arr[0]);

引用的本质

引用的本质就是指针

引用和指针的区别

  1. 引用必须初始化,而且只能指向一个变量。
  2. 对引用赋值,是对其指向的变量进行赋值,而不是修改引用本身的值。
  3. 对引用做运算,是对其指向的变量做运算,而不是对引用本身做运算。
  4. 引用类型就是一个"弱化了的指针"。

引用在函数参数传递中的作用(基本类型)

#include <iostream>

void Plus(int& i)
{
    i++;
    return;
}

int main()
{
    int i = 10;

    Plus(i);

    printf("%d\n", i);

    return 0;
}

引用在函数参数传递中的作用(构造类型)

#include <iostream>

struct Base
{
    int x;
    int y;

    Base(int x, int y)
    {
        this->x = x;
        this->y = y;
    }
};

void PrintByRef(Base& refb, Base* pb)
{
    //通过指针读取
    printf("%d %d\n", pb->x, pb->y);

    //通过引用读取
    printf("%d %d\n", refb.x, refb.y);

    //可以重新赋值、做运算吗?
    //refb = (Base&)1;
    //refb++;

    return;
}

常引用

  1. 引用是为了避免对指针进行错误的操作。
  2. 常引用是为了对一个对象进行只读操作,它指向的内容也不希望被修改。
#include <iostream>

class Base
{
public:
    int x;
};

void PrintA(Base& ref)
{
    //ref = 100;        //不能修改
    //ref.x = 200       //可以修改引用指向的内容
    printf("%d\n", ref.x);

    return;
}

//常引用
void PrintB(const Base& ref)
{
    //ref = 100;        //不能修改
    //ref.x = 200       //不能修改引用指向的内容
    printf("%d\n", ref.x);

    return;
}

int main()
{
    Base b;
    b.x = 100;
    PrintA(b);

    return 0;
}

总结

引用解决了指针能被读取/修改,导致的程序崩溃或出错。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值