C++形參傳入樣本

來源:互聯網
上載者:User
void add(int *a){(*a) = (*a) -5 ;}//值傳遞,將實參的一個副本作為函數形參傳遞給函數void swapValue(int a,int b){int temp=a;a =b;b=temp;}//指標傳遞參數,將實參的地址傳遞給函數內部,雖然作了副本傳入,但是改變是仍是實參地址上的值。void swapByPointer(int *a, int *b){int temp = *a;*a=*b;*b=temp;}//引用傳遞,此時傳遞給函數的是由主調函數放進來的實參變數的地址.//被調函數對形參的任何操作都被處理成間接定址,即通過棧中存放的地址訪問主調函數中的實參變數。// 正因為如此,被調函數對形參做的任何操作都影響了主調函數中的實參變數void swapByRef( int &a, int &b){int temp = a;a = b;b=temp;}//傳遞指向指標的引用,實現兩個指標的交換。void swapByPointerRef(int * &a, int *&b){int *temp = a;a=b;b=temp;}int main(){int a = 10;int b = 20;int *pa = &a;int *pb = &b;cout<<"a = "<<a<<"  b = "<<b<<endl;cout<<"*pa = "<<*pa<<" *pb = "<<*pb<<endl;cout<<"pa = "<<pa<<" pb = "<<pb<<endl;add(&a);cout<<"===a = "<<a<<endl;swapValue(a,b);cout<<endl<<"swapValue \n";cout<<"a = "<<a<<"  b = "<<b<<endl;cout<<"*pa = "<<*pa<<" *pb = "<<*pb<<endl;cout<<"pa = "<<pa<<" pb = "<<pb<<endl;swapByPointer(&a,&b);cout<<"\n swapByPointer  \n";cout<<"a = "<<a<<"  b = "<<b<<endl;cout<<"*pa = "<<*pa<<" *pb = "<<*pb<<endl;cout<<"pa = "<<pa<<" pb = "<<pb<<endl;swapByRef(a,b);cout<<"\n swapByRef  \n";cout<<"a = "<<a<<"  b = "<<b<<endl;cout<<"*pa = "<<*pa<<" *pb = "<<*pb<<endl;cout<<"pa = "<<pa<<" pb = "<<pb<<endl;swapByPointerRef(pa,pb);cout<<"\n swapByPointerRef \n";cout<<"a = "<<a<<"  b = "<<b<<endl;cout<<"*pa = "<<*pa<<" *pb = "<<*pb<<endl;cout<<"pa = "<<pa<<" pb = "<<pb<<endl;return 0;}

輸出結果:a = 10  b = 20*pa = 10 *pb = 20pa = 0012FF60 pb = 0012FF54===a = 5swapValuea = 5  b = 20*pa = 5 *pb = 20pa = 0012FF60 pb = 0012FF54 swapByPointera = 20  b = 5*pa = 20 *pb = 5pa = 0012FF60 pb = 0012FF54 swapByRefa = 5  b = 20*pa = 5 *pb = 20pa = 0012FF60 pb = 0012FF54 swapByPointerRefa = 5  b = 20*pa = 20 *pb = 5pa = 0012FF54 pb = 0012FF60

 

聯繫我們

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