c++ 引用

來源:互聯網
上載者:User

標籤:turn   空間   c++   wap   複製   int   實參   code   改變   

  • 引用
    • 引用符 —— &
    • 引用必須進行初始化
    • 一旦進行初始化,以後都不會改變其指向
  • 使用
    •   作為函數的參數  ——  不會佔用額外的空間,能提升函數的執行效率
      • #include <iostream>using std::endl;using std::cout;//引用函數作為參數void swap(int a, int b)//形參,參數傳遞的方式是值傳遞-->就是進行複製{//初始化形參:int a = x;int b = y;    int temp = a;    a = b;    b = temp;}//不會交換x/y的值//地址傳遞--》值傳遞void swaq(int *pa, int *pb){    int temp = *pa;    *pa = *pb;    *pb = temp;}//地址傳遞//引用傳遞//好處:不會佔用額外的空間,能夠提升執行效率void swal(int & ref1, int & ref2){//形參初始化:int & ref1 = a;int & ref2 = b;    int temp = ref1;    ref1 = ref2;    ref2 = temp;}int main(){    int x = 10;    int y = 20;    cout << "x = " << x << endl;    cout << "y = " << y << endl;    swap(x , y);//實參    cout << "進行交換之後" << endl;    cout << "x = " << x<< endl;    cout << "y = " <<y<<endl;    swaq(&x,&y);//實參    cout << "進行交換之後" << endl;    cout << "x = " << x << endl;    cout << "y = " << y << endl;    swal(x, y);//實參    cout << "進行交換之後" << endl;    cout << "x = " <<x<< endl;    cout << "y = " <<y<< endl;    system("pause");    return 0;}

         

        •   引用可以作為函數的傳回值
            •    當return語句執的時候,也不會進行複製,會返回變數本身
            • #include <iostream>using std::endl;using std::cout;int arr[5] = { 0,1,2,3,4 };int & func(int idx){    return arr[idx];}int main(){        func(0) = 10;    cout << arr[0] << endl;    system("pause");    return 0;}

               

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.