c++中地址和引用的區別

來源:互聯網
上載者:User

請看此例,使用vc6.0

#include "stdafx.h"
#include<iostream>
using namespace std;

void swap2(int& a,int& b);//聲明;引用
void swap3(int* a,int* b);

void swap2(int& a,int& b)//定義;引用
...{
    int temp=a;
    a=b;
    b=temp;
};

void swap3(int* a,int* b)
...{
    int p=*a;
    *a=*b;
    *b=p;
}

int main(int argc, char* argv[])
...{
/**/////////////////////////////////////////////////
    int a=2,b=10;
    cout<<a<<","<<b<<endl;
    //swap2(&a,&b);//不可以
    swap2(a,b);//引用
    //swap2(a+1,b);//不可以
    cout<<a<<","<<b<<endl;

    int *pa,*pb;
    pa = &a;//地址
    pb = &b;
    cout<<*pa<<","<<*pb<<endl;
    //swap2(pa,pb);//不可以(a)
    swap2(*pa,*pb);//引用
    cout<<*pa<<","<<*pb<<endl;
/**//////////////////////////////////////////////////

    int c=6,d=3;
    cout<<c<<","<<d<<endl;
    swap3(&c,&d);//地址
    cout<<c<<","<<d<<endl;


    int *pc,*pd;
    pc = &c;//地址
    pd = &d;
    cout<<*pc<<","<<*pd<<endl;
    swap3(pc,pd);
    //swap3(pc+1,pd);//(b)可以編譯通過,但顯然錯誤而危險,可以和(a)對比
    cout<<*pc<<","<<*pd<<endl;

/**///////////////////////////////////////////////////////

    c =23;d=67;
    //int &e,&f;//不可以,引用變數必需初始化
    int &e=c,&f=d;//引用;可以理解為e是c的別名

    cout<<e<<","<<f<<endl;
    swap2(e,f);
    cout<<e<<","<<f<<endl;

    cout<<e<<","<<f<<endl;
    swap3(&e,&f);//地址
    cout<<e<<","<<f<<endl;

    return 0;
}

由上,我的個人經驗:

//在聲明和定義中使用“&”時,是引用;在執行代碼中使用“&”時,是地址。
//不過對於如下語句:
//int *pc = &c;
//依然是地址。因為這個初始化動作也是執行代碼。

//其實引用、地址以及指標關係很緊密的。像int & a,const int *p, int *const p, const int * const p以及
//HANDLE控制代碼等,都可以理解為限制對指標的操作,以避免指標的弊端。
//由(a),(b)處可以看出引用要安全些。

//請指正。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.