/*Writted by Bruth_Lee in Southwest universiy of Science and Technology.
相关知识:指针、引用
Writed by Bruth_Lee
*/
#include<iostream>
using namespace std;
int main()
{
int a=6;
int b=5;
void swap1(int x,int y);
void swap2(int*x,int*y);
void swap3(int*x,int*y);
void swap4(int*&x,int*&y);
swap1(a,b);
cout<<"-----test1-----"<<endl;
cout<<a<<" "<<b<<endl;
swap2(&a,&b);
cout<<"-----test2-----"<<endl;
cout<<a<<" "<<b<<endl;
a=6,b=5;
int *p=&a;
int *q=&b;
cout<<"-----test3-----"<<endl;
swap3(&a,&b);
cout<<*p<<" "<<*q<<endl;
cout<<"-----test4-----"<<endl;
swap4(p,q);
cout<<*p<<" "<<*q<<endl;
return 0;
}
void swap1(int x,int y)//传入x,y的值,由于都是形参,所以只有在swap内部发生了交换
{
int z;
z=x;x=y;y=z;
}
void swap2(int *x,int *y)//传入了x,y的 地址,交换的是x,y的 值,并将其带出,a,b的地址并未发生改变
{
int t=*x;
t=*x;
*x=*y;
*y=t;
}
void swap3(int *x,int *y)//交换的是x,y 指针,想交换的是x,y 指针,在swap内部起到了交换作用,但是一离开swap,结果又还原了
{
int *z=NULL;
z=x;
x=y;
y=z;
}
//所以这个时候就要用到指针的引用了
void swap4(int *&x,int *&y)//传入了x,y的地址,改变的是x,y的地址,注意此时的操作是引用
{
int *z=NULL;
z=x;
x=y;
y=z;
}