函式傳值的三種方法
阿新 • • 發佈:2018-12-26
第一種:
#include <iostream>
using namespace std;
void myswap(int x,int y)
{
int t;
t=x;
x=y;
y=t;
}
int main()
{
int a,b;
cout<<"請輸入帶交換的兩個整數"<<endl;
cin>>a>>b;
myswap(a,b);
cout<<"呼叫交換函式後的結果是:"<<endl;
cout<<a<<" "<<b<<endl;
return 0;
}
執行結果:
註釋:該方法在呼叫myswap函式時開闢的記憶體空間在函式呼叫結束時會釋放掉,因此沒有起到傳值的效果。
第二種:
#include <iostream>
using namespace std;
void myswap(int *p1,int *p2)
{
int t;
t=*p1;
*p1=*p2;
*p2=t;
}
int main()
{
int a,b;
cout<<"請輸入帶交換的兩個整數"<<endl;
cin>>a>>b;
myswap(&a,&b);
cout<<"呼叫交換函式後的結果是:"<<endl;
cout<<a<<" "<<b<<endl;
return 0;
}
執行結果:
註釋:此方法中,運用指標,呼叫函式時,將變數的地址交換,成功起到了數值的交換。
第三種:
#include <iostream>using namespace std;
void myswap(int &x,int &y)
{
int t;
t=x;
x=y;
y=t;
}
int main()
{
int a,b;
cout<<"請輸入帶交換的兩個整數"<<endl;
cin>>a>>b;
myswap(a,b); cout<<"呼叫交換函式後的結果是:"<<endl;
cout<<a<<" "<<b<<endl;
return 0;
} 執行結果: