以swap作为媒介理解一下函数条件与全局变量、指针、引用的联系
换不了(典例)
#include <iostream>
using namespace std;
void swap()
{
int temp = x;
x = y;
y = temp;
}
int main()
{
int x = 5,y = 6;
swap();
cout<<x<<" "<<y;
return 0;
}
以下是 4 种swap的方法:
全局变量
#include <iostream>
using namespace std;
int x = 5,y = 6;
void swap()
{
int temp = x;
x = y;
y = temp;
}
int main()
{
swap();
cout<<x<<" "<<y;
return 0;
}
指针
#include <iostream>
using namespace std;
void swap(int* x,int* y)
{
int temp = *x;
*x = *y;
*y = temp;
}
int main()
{
int x = 5,y = 6;
swap(&x,&y);
cout<<x<<" "<<y;
return 0;
}
引用
#include <iostream>
using namespace std;
void swap(int& x,int& y)
{
int temp = x;
x = y;
y = temp;
}
int main()
{
int x = 5,y = 6;
swap(x,y);
cout<<x<<" "<<y;
return 0;
}
数组
#include <iostream>
using namespace std;
void swap(int a[],int x,int y)//其实等价于 void swap(int*a,int x,int y),原理是指针
{
int temp = a[x];
a[x] = a[y];
a[y] = temp;
}
int main()
{
int a[2] = {5,6};
int x = 0,y = 1;
swap(a,x,y);
cout<<a[x]<<" "<<a[y];
return 0;
}