例子如下:
#include<iostream>
using namespace std;
void swap1(int c, int d) {
cout << "swap1中:&c=" << &c << " &d=" << &d << endl;
cout << "swap1中:c=" << c << " d=" << d << endl;
int tmp = c;
c = d;
d = tmp;
}
void swap2(int &c, int &d) {
cout << "swap2中:&c=" << &c << " &d=" << &d << endl;
cout << "swap2中:c=" << c << " d=" << d << endl;
int tmp = c;
c = d;
d = tmp;
}
void swap3(int* c, int* d) {
cout << "swap3中:&c=" << &c << " &d=" << &d << endl;
cout << "swap3中:c=" << c << " d=" << d << endl;
int* tmp = c;//因为这里的c是指针,所以tmp也得是指针类型
c = d;
d = tmp;
cout << "swap3中执行完函数内交换:c=" << c << " d=" << d << endl;
}
void swap4(int* c, int* d) {
cout << "swap4中:&c=" << &c << " &d=" << &d << endl;
cout << "swap4中:c=" << c << " d=" << d << endl;
cout << "swap4中:*c=" << *c << " *d=" << *d << endl;
cout << "swap4中:&(*c)=" << &*c << " &(*d)=" << &*d << endl;
int tmp = *c;//因为*c已经取值了,所以这里的tmp为int类
*c = *d;
*d = tmp;
}
int main(){
int a, b;
cin >> a >> b; //5 6
cout << "原值中,&a=" << &a << " &b=" << &b << endl;//输出a,b的地址
swap1(a, b); //5 6
swap2(a, b); //6 5
swap3(&a, &b); //5 6
swap4(&a, &b); //6 5
cout << "交换后:" << a << " " << b;
return 0;
}
调用swap1时:swap1(int c ,int d)
在内存中另外开辟两个空间叫c,d,相当于传值调用。
int tmp = c;
c = d;
d = tmp;
调用swap2时:swap2(int &c ,int &d)
此时的c,d就是main中的 a,b,相当于引用(把a,b带进来)。
int tmp = c;
c = d;
d = tmp;
调用swap3时:swap3(int * c ,int * d)
在此函数中c,d是个指针,存放的就是main中a,b的地址。
函数中的 c 存放 main 中 a 的地址,函数中的 d 存放 main 中的 b 的地址
int* tmp = c;
c = d;
d = tmp;
执行完这个代码:只是把 c,d 中存放的东西换了,而没有改变 a ,b(此时 c 存放 mian 中 b 的地址,d 存放 main 中 a 的地址)
调用swap4时:swap4(int * c ,int * d)
在此函数中c,d是个指针,存放的就是main中a,b的地址。
函数中的 c 存放 main 中 a 的地址,函数中的 d 存放 main 中的 b 的地址
//这里就不是交换存放的地址,而是交换这个地址下的值
int tmp = *c;//因为*c已经取值了,所以这里的tmp为int类
*c = *d;
*d = tmp;