c++引用問題

來源:互聯網
上載者:User

標籤:c++引用

1、整型變數的引用

程式如下:

#include <stdlib.h>

#include <iostream>

using namespace std;int main(){int a=10;int &b=a; b=200;//此處變數賦值不能int ,否則重定義cout<<"此時a的值是;"<<a<<endl; a=100;cout <<"此時b的值是:"<<b<<endl;system("pause");return 0;}

650) this.width=650;" src="https://s2.51cto.com/wyfs02/M00/05/75/wKiom1mlXIHhUW_xAAAWeyiihFU379.png" title="無標題.png" alt="wKiom1mlXIHhUW_xAAAWeyiihFU379.png" />

標明,引用無非就是給已經出現的變數定義了一個別名。所以在程式執行的過程中,對原來的變數做何種操作和對於他唯一的別名做什麼操作,其實是別無二致的事情,因為本質上,兩者是一種東西。

2、結構中的引用

#include <stdlib.h>#include <iostream>using namespace std;typedef struct{int x;int y;}COORD;//結構體的定義,這是結構體的名字、int main(){COORD c;//結構體類型的c.COORD &c1=c;//資料類型就是結構體名,然後按格式&別名c1.x=10;c1.y=29;cout<<c.x<<endl<<c.y<<endl;system("pause");return 0;}

運行結果:

650) this.width=650;" src="https://s2.51cto.com/wyfs02/M02/A4/27/wKioL1mlYFKjUKgKAAAGnhScTvg702.png" title="無標題.png" alt="wKioL1mlYFKjUKgKAAAGnhScTvg702.png" />

注意的問題:結構體的定義、結構體引用時,就結構體名就相當於資料類型。

3、指標中的引用

#include <stdlib.h>#include <iostream>using namespace std;int main(){int a=10; int *p=&a;//定義一個指標p,它指向a.注意& int *&q=p;指標類型引用的格式:資料類型 * & 別名=原來指標*q=5;//注意不能前面再加資料類型,否則出現重複定義cout <<a<<endl;system("pause");return 0;}

運行結果:

650) this.width=650;" src="https://s2.51cto.com/wyfs02/M00/05/77/wKiom1mlbFDTzl7IAAAGOxlioOM071.png" title="無標題.png" alt="wKiom1mlbFDTzl7IAAAGOxlioOM071.png" />

4、引用後的別名作為函數參數

代碼:

#include <stdlib.h>#include <iostream>using namespace std;//聲明一個具有交換功能的函數void fun(int &a,int &b);//a,b分別是實際參數的別名,作為形參使用,注意起別名的時候一定要加資料類型的啊int main(){int x=10;int y=20;cout <<x<<","<<y<<endl; fun(x,y);cout<<x<<","<<y<<endl;system("pause");return 0;}void fun (int &a,int &b){int c=0;c=a;a=b;b=c;};運行結果:

650) this.width=650;" src="https://s5.51cto.com/wyfs02/M01/A4/28/wKioL1mlb2Cj3QKzAAALJFYBe3A724.png" title="無標題.png" alt="wKioL1mlb2Cj3QKzAAALJFYBe3A724.png" />

今天主要學習了c++的幾種引用的類型,搞清楚沒種引用相應的格式類型,理解也很容易。今天的學習到此為止。

c++引用問題

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.