浅谈C++之引用


C++中,引用(reference)是已存在变量的别名(alias),通过引用,可间接访问变量,指针也可以,但引用在使用上更加安全。引用的主要用途是描述函数的参数和返回值,特别是传递较大的数据变量。

定义:

语法格式:

数据类型 & 引用变量名 = 变量名;

eg:

int x;

int &refx=x;

运用引用交换两个变量的值。

/**
  * 行有余力,则来刷题!
  * 博客链接:http://blog.csdn.net/hurmishine
  *
*/
#include <iostream>
#include <cstdio>
using namespace std;

void Myswap(int &x,int &y)
{
    int t=x;
    x=y;
    y=t;
}
int main()
{
    int x=10,y=20;
    cout<<"x="<<x<<",y="<<y<<endl;
    Myswap(x,y);
    cout<<"x="<<x<<",y="<<y<<endl;
    
    return 0;
}


引用作为函数参数和返回值。

/**
  * 行有余力,则来刷题!
  * 博客链接:http://blog.csdn.net/hurmishine
  *
*/
#include <iostream>
#include <cstdio>
using namespace std;
void fun(int x,int &y)//函数参数为引用
{
    y=x;
}
int &sum(int x,int y)//函数返回值为引用
{
    int z=x+y;
    return z;
    //注:以上改为: return x+y;则无法编译
}

int main()
{
    int x=10;
    int y=20;
    int &z=y;//引用,z的值与y绑定,y改变则x也一起改变,反之亦然
    cout<<"x="<<x<<",y="<<y<<endl;  //x=10,y=20
    cout<<"z="<<z<<endl;    //z=20

    fun(x,y);
    cout<<"x="<<x<<",y="<<y<<endl;  //x=10,y=10
    cout<<"z="<<z<<endl;    //z=10

    z=50;
    cout<<"x="<<x<<",y="<<y<<endl;  //x=10,y=50
    cout<<"z="<<z<<endl;    //z=50

    y=100;
    cout<<"x="<<x<<",y="<<y<<endl;//x=10,y=100
    cout<<"z="<<z<<endl;//100

    //函数返回值为引用,可作为左值参与运算,但他本身的值不发生改变。
    int a=10,b=20;
    cout<<sum(a,b)<<endl;   //30

    cout<<--sum(a,b)<<endl; //29

    cout<<++sum(a,b)<<endl; //31

    cout<<sum(a,b)--<<endl; //30

    cout<<sum(a,b)++<<endl; //30

    sum(a,b)+=10;
    cout<<sum(a,b)<<endl;//30
    return 0;
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值