zoukankan      html  css  js  c++  java
  • 什么是引用,如何使用引用?使用引用作为函数参数,相关例题

    什么是引用?

    int a;

    int &b=a;

    上边就是变量的引用

    符号&不是去地址的含义了,去地址是在指针时的含义,这里表示引用。(这个引用不是动词,而是名词)

    引用的定义:对一个数据可以建立一个“引用”,它的作用是为一个变量起一个别名。

    int &b=a;

    以上声明了b是a的引用,即b是a的别名。

    &符号的作用此时称为引用声明符,并不代表地址。

    比较一下指针的使用:

    int a=30;

    int *p=&a;

    cout<<*p;


    int a=30;

    int &b=a;

    cout<<b;

    注意:声明一个引用时,必须同时使他初始化。表明他是谁的别名。


    例题:通过引用得到变量的值。

    #include <iostream>
    #include <iomanip>
    using namespace std;
    
    int main(){
        
        int a=10;
        int &b=a;
        a=a*a;
        cout<<a<<setw(6)<<b<<endl;
        b=b/5;
        cout<<b<<setw(6)<<a<<endl;
        
        return 0;
    }

    使用引用作为函数参数

    例题:将变量i和j的值互换。

    首先看交换失败的程序:

    #include <iostream>
    #include <iomanip>
    using namespace std;
    
    void swap(int a,int b){
        int temp;
        temp=a;
        a=b;
        b=temp;
    }
    
    int main(){
        
        int i=3,j=5;
        swap(i,j);
        cout<<i<<" "<<j<<endl;
        return 0;
    }

    接着使用指针的方法来进行交换的程序:

    #include <iostream>
    #include <iomanip>
    using namespace std;
    
    void swap(int *p1,int *p2){
        int temp;
        temp=*p1;
        *p1=*p2;
        *p2=temp;
    }
    
    int main(){
        
        int i=3,j=5;
        swap(&i,&j);
        cout<<i<<" "<<j<<endl;
        return 0;
    }

    最后,使用引用的方法来进行交换的程序:

    #include <iostream>
    #include <iomanip>
    using namespace std;
    
    void swap(int &a,int &b){
        int temp;
        temp=a;
        a=b;
        b=temp;
    }
    
    int main(){
        
        int i=3,j=5;
        swap(i,j);
        cout<<"i="<<i<<" "<<"j="<<j<<endl;
        return 0;
    }
  • 相关阅读:
    ld: cannot find lgcc_s
    Ubuntu 12.10 图形显示未知
    awk分析Nginx日志中的cookie
    Ubuntu 10.04 WPS 问题汇总
    objc[20556]:Class JavaLaunchHelper is implemented in both xxx 警告处理
    在Linux安装配置Tomcat 并部署web应用 ( 三种方式 )
    Spring Boot 系列(二)单元测试&网络请求
    Java自定义注解
    Spring Boot 系列(一)快速入门
    Spring 自定义注解,配置简单日志注解
  • 原文地址:https://www.cnblogs.com/qingyundian/p/8041259.html
Copyright © 2011-2022 走看看