C++ 引用

1、引用的声明

#include<iostream>
using namespace std;
int main()
{
    int a = 12;
    int& c = a;// 声明变量a的一个引用c,c是变量a的一个别名,C++中引用的声明,&表示引用
    int& d = a;// 引用d必须要初始化;
    c = 1;
    cout << a << endl;

    //数组的引用
    int arr[12];
    int(&p)[12] = arr;//引用 类型
    p[1] = 16;
    cout << arr[1] << endl;

    //二维数组
    int arr2[2][4];
    int(&p1)[2][4] = arr2;
    p1[1][2] = 123;
    cout << arr2[1][2]<< endl;

    //指针的引用
    int b = 12;
    int* point = &b;
    int* (&p2) = point;
    *p2 = 1234;
    cout <<b<< endl;

    return 0;
}

2、引用做参数

#include<iostream>
using namespace std;
void fun(int& a)//a是b的引用
{
    a = 133;
    cout <<"这是fun:"<<a << endl;
}
void fun1(int* a)//这是操纵地址
{
    *a = 13;
    cout <<"这是fun1:"<< *a << endl;
}

int main()
{
    int b = 12;
    fun(b);
    cout << b << endl;
    fun1(&b);
    cout << b << endl;

    system("pause");
    return 0;
}

3、利用引用、地址实现交换

#include <iostream>
using namespace std;
void ExChange(int& j, int& k)//引用的声明做参数来交换两个变量的值
{
    int nTemp = j;
    j = k;
    k= nTemp;
}
void ExChange1(int& j, int& k)//根据地址来交换值
{
    int nTemp = j;
    j = k;
    k = nTemp;
}
int main()
{
    int a = 12,
        b = 14;
    cout << "a:" << a << endl;
    cout << "b:" << b << endl;
    ExChange(a, b);
    cout << "第一次交换" << endl;
    cout << "a:" << a << endl;
    cout << "b:" << b << endl;
    
    ExChange(a, b);
    cout << "第二次交换" << endl;
    cout << "a:" << a << endl;
    cout << "b:" << b << endl;

    system("pause");
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

clown_30

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值