用指针来写:
void swap(int* x,int* y)
{
int temp;
temp=*y;
*y=*x;
*x=temp;
}
int main()
{
int a,b;
int* pa=&a;
int* pb=&b;
cout<<"请输入两个整数"<<endl;
cin>>a>>b;
cout<<"a="<<a<<" "<<"b="<<b<<endl;
swap(pa,pb);
cout<<"a="<<a<<" "<<"b="<<b<<endl;
return 0;
}
用引用来写
void swap( int &x,int &y)
{
int temp;
temp=y;
y=x;
x=temp;
}
int main()
{
int a,b;
cout<<"请输入两个整数"<<endl;
cin>>a>>b;
cout<<"a="<<a<<" "<<"b="<<b<<endl;
int &refa=a;
int &refb=b; //引用也需要定义
swap(refa,refb);
cout<<"a="<<a<<" "<<"b="<<b<<endl;
return 0;
}