效果来看:两者都会改变实参,效果基本相同
使用来看:指针更复杂
建议使用引用的方式
//1. 值传递,原始的a b值不改变
void mySwap01(int a, int b) {
int temp = a;
a = b;
b = temp;
}
//2. 地址传递,原始的a b值改变
void mySwap02(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
//3. 引用传递,原始的a b值改变
void mySwap03(int& a, int& b) {
int temp = a;
a = b;
b = temp;
}
int main() {
int a = 10;
int b = 20;
mySwap01(a, b);
cout << "a:" << a << " b:" << b << endl;
mySwap02(&a, &b);
cout << "a:" << a << " b:" << b << endl;
mySwap03(a, b);
cout << "a:" << a << " b:" << b << endl;
system("pause");
return 0;
}