C++引用

來源:互聯網
上載者:User

標籤:style   color   函數調用   時空   基礎上   amp   調用   c++   傳回值   

大家都知道,C++ 語言有一種 很好用的 也是很常用的技術 叫做引用,這個是在C語言的基礎上的一個擴沖,類似指標,只是在聲明的時候用&取代了* , 引用可以看作是被引用的一個別名,在聲明時必須同時進行初始化。

1.函數參數的引用

 

 

#include<iostream>using namespace std;void swap(int &a, int &b);int main(){    int num1 = 10;    int num2 = 20;    cout<<num1<<" "<<num2<<endl;    swap(num1, num2);    cout<<num1<<" "<<num2<<endl;    return 0;}void swap(int &a, int &b){    int temp = a;    a = b;    b = temp;}

 

2.函數引用傳回值

在C++中非void型函數需要返回一個傳回值,類似函數形參,我們同樣可以將函數的傳回值聲明為引用。普通的函數傳回值是通過傳值返回,即將關鍵字return後面緊接的運算式運算結果或變數拷貝到一個臨時儲存空間中,然後函數調用者從臨時儲存空間中取到函數傳回值。

#include<iostream>using namespace std;int valplus(int &a);int main(){    int num1 = 10;    int num2;    num2 = valplus(num1);    cout<<num1<<" "<<num2<<endl;    return 0;}int valplus(int &a){    a = a + 5;    return a;}

 

valplus函數採用的是普通的傳值返回,也即將變數a的結果加上5之後,將結果拷貝到一個臨時儲存空間,然後再從臨時儲存空間拷貝給num2變數。 當我們將函數傳回值聲明為引用的形式時,如例5所示。雖然例5運行結果和例4是相同的,但例5中的valplus函數在將a變數加上5之後,其運算結果是直接拷貝給num2的,中間沒有經過拷貝給臨時空間,再從臨時儲存空間中拷貝出來的這麼一個過程。這就是普通的傳值返回和引用返回的區別。

#include<iostream>using namespace std;int & valplus(int &a);int main(){    int num1 = 10;    int num2;    num2 = valplus(num1);    cout<<num1<<" "<<num2<<endl;    return 0;}int & valplus(int &a){    a = a + 5;    return a;}

 

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.