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