例子如下:
#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;