1、传引用
引用是变量的一个别名,跟变量共用内存空间
#include <iostream>
using namespace std;
void swap(int& a,int& b) {
cout << "a的值为:" << a << " b的值为:" << b << endl;
cout << "swap函数中a的地址为:" << &a << " b的地址为:" << &b << endl << endl;
int temp = a;
a = b;
b = temp;
cout << "a的值为:" << a << " b的值为:" << b << endl;
cout << "交换后swap函数中a的地址为:" << &a << " b的地址为:" << &b << endl << endl;
}
int main() {
int a = 1;
int b = 2;
cout << "a的值为:" << a << " b的值为:" << b << endl;
cout << "a的地址为:" << &a << " b的地址为:" << &b << endl << endl;
swap(a, b);
cout << "调用swap函数后a的值为:" << a << " b的值为:" << b << endl << endl;
system("PAUSE");
return 0;
}
运行结果
可以看到变量的值发生变化,地址都没有变化,也就是说并没有开辟新的内存空间,改变swap函数的形参会直接影响到实参
2、传指针
#include <iostream>
using namespace std;
void swap(int* a, int* b) {
cout << "a的值为:" << a << " b的值为:" << b << endl;
cout << "a指向对象的值为:" << *a << " b指向对象的值为:" << *b << endl;
cout << "swap函数中a的地址为:" << &a << " b的地址为:" << &b << endl << endl;
int temp = *a;
*a = *b;
*b = temp;
cout << "a的值为:" << a << " b的值为:" << b << endl;
cout << "a指向对象的值为:" << *a << " b指向对象的值为:" << *b << endl;
cout << "交换后swap函数中a的地址为:" << &a << " b的地址为:" << &b << endl << endl;
}
int main() {
int a = 1;
int b = 2;
cout << "a的值为:" << a << " b的值为:" << b << endl;
cout << "a的地址为:" << &a << " b的地址为:" << &b << endl << endl;
swap(&a, &b);
cout << "调用swap函数后a的值为:" << a << " b的值为:" << b << endl;
system("PAUSE");
return 0;
}
运行结果
可以看到,在swap函数中为形参开辟了一块新的内存空间,将实参的地址传进去,swap函数交换a,b指针指向对象的值,即修改了实参。