值传递
#include<iostream>
using namespace std;
void swap(int x, int y)
{
cout << "x的地址是:" << &x << " " << "y的地址是:" << &y<< endl;
int temp;
cout << endl;
cout << "temp的地址是:" << &temp<<endl;
temp = x, x = y, y = temp;
}
int main()
{
int a, b;
a = 3, b = 4;
cout << "a的地址是:" << &a << " " << "b的地址是:" << &b << endl;
cout << endl;
swap(a, b);
cout << endl;
cout << a << " " << b << endl;
return 0;
}
输出:
a的地址是:000000837EEFF9B4 b的地址是:000000837EEFF9D4
x的地址是:000000837EEFF990 y的地址是:000000837EEFF998
temp的地址是:000000837EEFF894
3 4
C:\code\Project2\x64\Debug\Project2.exe (进程 7036)已退出,代码为 0。
按任意键关闭此窗口. . .
地址传递
#include<iostream>
using namespace std;
void swap(int *x, int *y)
{
cout << "x的地址是:" << x << " " << "y的地址是:" << y<< endl;
int temp;
cout << endl;
cout << "temp的地址是:" << &temp<<endl;
temp = *x, *x = *y, *y = temp;
}
int main()
{
int a, b;
a = 3, b = 4;
cout << "a的地址是:" << &a << " " << "b的地址是:" << &b << endl;
cout << endl;
swap(&a, &b);
cout << endl;
cout << a << " " << b << endl;
return 0;
}
输出:
a的地址是:0000009B6438F624 b的地址是:0000009B6438F644
x的地址是:0000009B6438F624 y的地址是:0000009B6438F644
temp的地址是:0000009B6438F504
4 3
C:\code\Project2\x64\Debug\Project2.exe (进程 17244)已退出,代码为 0。
按任意键关闭此窗口. . .
引用传递
#include<iostream>
using namespace std;
void swap(int &x, int &y)
{
cout << "x的地址是:" << &x << " " << "y的地址是:" << &y<< endl;
int temp;
cout << endl;
cout << "temp的地址是:" << &temp<<endl;
temp = x, x = y, y = temp;
}
int main()
{
int a, b;
a = 3, b = 4;
cout << "a的地址是:" << &a << " " << "b的地址是:" << &b << endl;
cout << endl;
swap(a, b);
cout << endl;
cout << a << " " << b << endl;
return 0;
}
输出:
a的地址是:00000054A93DF974 b的地址是:00000054A93DF994
x的地址是:00000054A93DF974 y的地址是:00000054A93DF994
temp的地址是:00000054A93DF854
4 3
C:\code\Project2\x64\Debug\Project2.exe (进程 6044)已退出,代码为 0。
按任意键关闭此窗口. . .