最經典的案例
寫一個交換函數,實現兩個數的交換
#include<iostream> using namespace std; void swap1(int a,int b) { int temp=a; a=b; b=temp; cout<<"函數內交換結果:"<<endl; cout<<"a 的值:"<<a<<endl; cout<<"b 的值:"<<b<<endl; cout<<endl; } int main() { int a=10,b=20; cout<<a<<" "<<b<<endl; cout<<"a和b的初值:"<<endl; cout<<"a 的值:"<<a<<endl; cout<<"b 的值:"<<b<<endl; cout<<endl; swap1(a,b); cout<<"調用函數後的結果:"<<endl; cout<<"a 的值:"<<a<<endl; cout<<"b 的值:"<<b<<endl; cout<<endl; return 0; }
運行結果:
結果分析:很明顯經過上面那個函數並沒有實現想要的結果。
原因:採取上述傳參,只是相當於把實參賦給了形參,但是形參並不影響實參,就像C++裏面的語句:a=b;
這只是把b的值賦給a,但是對b並沒有啥影響。
指針傳遞
#include<iostream> using namespace std; int swap1(int *p1,int *p2) { int temp=*p1; *p1=*p2; *p2=temp; cout<<"函數內交換結果:"<<endl; cout<<"a 的值:"<<*p1<<endl; cout<<"b 的值:"<<*p2<<endl; cout<<endl; } int main() { int a=10,b=20; cout<<"a和b的初值:"<<endl; cout<<"a 的值:"<<a<<endl; cout<<"b 的值:"<<b<<endl; cout<<endl; swap1(&a,&b); cout<<"調用函數後的結果:"<<endl; cout<<"a 的值:"<<a<<endl; cout<<"b 的值:"<<b<<endl; cout<<endl; return 0; }
運行結果:
結果分析:成功實現了交換
原因:對於寫函數時候,函數的參數有指針(*p),調用函數時,傳參傳了一個地址( &a ),
可以這樣理解 int *p=&a; 經過傳參這個過程,就好比進行了一個指針的定義和賦值,實參的傳遞爲函數爲函數提供了一個地址,在函數內部可以對這個地址進行操作(可以改變地址的值或者進行賦值操作),這樣一來,在函數裏面進行交換,結果就能影響主函數的交換了(交換函數實現的本質)。