C++之引用

引用

  • 普通变量引用
  • 结构体类型引用
  • 指针类型引用
  • 引用做函数参数
  • 引用和指针的区别

变量类型引用

#include <iostream>
using namespace std;
int main(void)
{
    int a = 5;
    int &b = a; //引用必须初始化
    b = 10;
    cout << a << endl; //10 
    return 0;
}

结构体类型引用

#include <iostream>
using namespace std;

typedef struct
{
    int x;
    int y;
}Coor;

int main(void)
{
    Coor c1;
    Coor &c = c1;
    c.x = 5;
    c.y = 10;
    cout << c1.x << c1.y << endl;// 5 10
    return 0;
}

指针类型引用

using namespace std;
int main(void)
{
    int a = 5;
    int *p = &a; 
    int *&q = p; //引用必须初始化
    *q = 10;
    cout << a << endl; //10
    system("pause");
    return 0;
}

引用做函数参数

#include <iostream>
using namespace std;
void fun(int &a,int &b)
{
    int c = 0;
    c = a;
    a = b;
    b = c;
}
int main(void)
{
    int x = 5, y = 21;
    cout << "x = " << x << endl; //5
    cout << "y = " << y << endl; //10
    fun(x, y);
    cout << "x = " << x << endl; //10
    cout << "y = " << y << endl; //5
    system("pause");
    return 0;
}

引用和指针的区别

待补充

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值