1.原理
传值调用:对形参进行函数变化
传地址调用:对实参进行函数变化
2.实例
#include<iostream>
using namespace std;
void exchange(int x, int y){ //传入形参
int temp = x; //在main函数中x=3,y=4
x = y;
y = temp;
printf("x=%d,y=%d\n", x, y);
}
void exchange1(int &x, int &y){ //传入地址
int temp = x; //在main函数中,x=&a,y=&b,即对a,b本身进行操作
x = y;
y = temp;
printf("x=%d,y=%d\n", x, y);
}
int g(int y){ //传值调用
y = y + 1;
return y;
}
int g1(int &y){ //传地址调用
y = y + 1;
return y;
}
void f(int x){
int a = 5;
a = g(x);
printf("a=%d,x=%d\n", a, x);
}
void f1(int x){
int a = 5;
a = g1(x);
printf("a=%d,x=%d\n", a, x);
}
void main(){
int a = 3;
int b = 4;
exchange(a, b); //此时有前缀操作x=a,y=b,此时x=3,y=4,对a和b本身不操作
printf("a=%d,b=%d\n", a, b); //a=3,b=4
exchange1(a, b); //此时有前缀操作x=&a,y=&b,此时x,y指向a,b的地址,即对a,b本身操作
printf("a=%d,b=%d\n", a, b); // a=4,b=3
f(1); //传值调用 a=2,x=1
f1(1); //传地址调用 a=2,x=2
}