要求:实现两个数据的交换。
#include<iostream>
using namespace std;
void swap1(int a,int b);
void swap2(int &a,int &b);
void swap3(int *a,int *b);
void swap4(int &a,int &b);
int main(){
int a=10,b=20;
cout<<"---------直接交换--------"<<endl;
swap1(a,b);
cout<<"a="<<a<<", b="<<b<<endl;
cout<<endl;
cout<<"---------引用交换--------"<<endl;
a=10;
b=20;
swap2(a,b);
cout<<"a="<<a<<", b="<<b<<endl;
cout<<endl;
cout<<"---------指针交换--------"<<endl;
a=10;
b=20;
swap3(&a,&b);
cout<<"a="<<a<<", b="<<b<<endl;
cout<<endl;
cout<<"---------二进制交换--------"<<endl;
a=10;
b=20;
swap4(a,b);
cout<<"a="<<a<<", b="<<b<<endl;
cout<<endl;
return 0;
}
void swap1(int a,int b){
int temp=a;
a=b;
b=temp;
}
void swap2(int &a,int &b){
int temp=a;
a=b;
b=temp;
}
void swap3(int *a,int *b){
int *temp=a;
a=b;
b=temp;
}
void swap4(int &a,int &b){
a=a^b;
b=a^b;
a=a^b;
}
通过测试只有利用引用才能实现两个数的交换,用指针和直接交换的方式都不行;swap4也是利用引用进行的,只不过是将a和b利用未运算的方式进行交换的,其中可以注意到没有中间变量,这样就可以节省一个存储空间,不过此方法只能用于两个整数进行数值交换。