c++传参
- 传值传参
- 把参数实际值传给函数的形参,这样,函数内修改函数对实际参数没有影响
- 指针传递和引用传递
- 把参数的地址或者引用赋值都传给形式参数。修改形式参数会改变实际参数。
#include <iostream>
//形式参数
void swap1(int a,int b);
// 传递指针
void swap(int *a,int *b);
//传递引用
void swap(int &a,int &b);
using namespace std;
int main(){
int a=2,b=3;
int c=2,d=3;
// 未发生变化
cout<<"global a is "<<a<<endl;
cout<<"global b is "<<b<<endl;
swap1(a,b);
cout<<"later!"<<endl;
cout<<"global a is "<<a<<endl;
cout<<"global b is "<<b<<endl;
cout<<"----------------------"<<endl;
// 发生变化
cout<<"global c is "<<c<<endl;
cout<<"global d is "<<d<<endl;
swap(&c,&d);
cout<<"later!"<<endl;
cout<<"global c is "<<c<<endl;
cout<<"global d is "<<d<<endl;
cout<<"----------------------"<<endl;
cout<<"global a is "<<a<<endl;
cout<<"global b is "<<b<<endl;
swap(a,b);
cout<<"later!"<<endl;
cout<<"global a is "<<a<<endl;
cout<<"global b is "<<b<<endl;
return 0;
}
void swap1(int a,int b){
int temp;
temp = a;
a = b;
b = temp;
cout<<"the inter a is "<<a<<endl;
cout<<"the inter b is "<<b<<endl;
};
void swap(int *a,int *b){
int temp;
temp = *a;
*a = *b;
*b = temp;
cout<<"the inter a is "<<*a<<endl;
cout<<"the inter b is "<<*b<<endl;
}
void swap(int &a,int &b){
int temp;
temp = a;
a = b;
b = temp;
cout<<"the inter a is "<<a<<endl;
cout<<"the inter b is "<<b<<endl;
}