C++ &引用用法

1.引用的内涵

  引用就是给变量取外号而已。

2.四种不能使用引用的情况

void &r=x; //不能建立void类型引用
int &&r=x; //不能建立引用的引用
int &*p=x; //不能建立指向引用的指针,但是可以建立指向指针的引用
int &ra[10]=a; //不能建立引用的数组
  总结:引用一有三无:有类型,无引用,无指针,无数组

3.引用的最基本用法

复制代码
#include<iostream>
using namespace std;
int x=5,y=10;
int &r=x;
void print()
{
    cout<<"x="<<x<<" y=<<y<<" r="<<endl;
    cout<<"Address of x "<<&x<<endl;
    cout<<"Address of y "<<&y<<endl;
    cout<<"Address of z "<<&z<<endl;
}
int main()
{
    print();
    r=y;
     
    y=100;
    print();
    x=200;
    print();
    return 0;
}
复制代码
复制代码
运行结果如下:
x=5 y=10 r=5 Address of x 00474DD0 Address of y 00474DD4 Address of r 00474DD0 x=10 y=100 r=10 Address of x 00474DD0 Address of y 00474DD4 Address of r 00474DD0 x=200 y=100 r=200 Address of x 00474DD0 Address of y 00474DD4 Address of r 00474DD0
复制代码
  总结:修改作用,引用==原变量

4.引用作为形参

  引用作形参,系统不为其另分配内存空间,与原变量公用内存空间。
  调用函数才初始化。
复制代码
 1 #include <iostream>
 2 using namespace std;
 3 void swap(int &x,int &y)
 4 {
 5     int t=x;
 6     x=y;
 7     y=t;
 8 }
 9 int main()
10 {
11     int a=3,b=5,c=10,d=20;
12     cout<<"a="<<a<<" b="<<b<<endl;
13     swap(a,b);
14     cout<<"a="<<a<<" b="<<b<<endl;
15     cout<<"c="<<c<<" d="<<d<<endl;
16     swap(c,d);
17     cout<<"c="<<c<<" d="<<d<<endl;
18     return 0;
19 }
复制代码

RESULT:

a=3 b=5
a=5 b=3
c=10 d=20
c=20 d=10

 

原文来自饼神的博客:http://my.oschina.net/zqmath1994/blog/506840

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值