swap函数实现
#include <iostream>
using namespace std;
void fun(int* a,int* b){
int t = *a;
*a = *b;
*b = t;
}
void fun(char* a,char* b){
char t = *a;
*a = *b;
*b = t;
}
void fun(double &a,double &b){
double t = a;
a = b;
b = t;
}
void fun(string &a,string &b){
string t = a;
a = b;
b = t;
}
int main()
{
//int
int num1 = 3, num2 = 4;
cout << "Before:" << "num1 = " << num1 << '\t' << "num2 = " << num2 << endl;
fun(&num1,&num2);
cout << "After:" << "num1 = " << num1 << '\t' << "num2 = " << num2 << endl;
cout << endl;
//cahr
char ch1 = 'a', ch2 = 'b';
cout << "Before:" << "ch1 = " << ch1 << '\t' << "ch2 = " << ch2 << endl;
fun(&ch1,&ch2);
cout << "After:" << "ch1 = " << ch1 << '\t' << "ch2 = " << ch2 << endl;
cout << endl;
//double
double var1 = 5.20, var2 = 13.14;
cout << "Before:" << "var1 = " << var1 << '\t' << "var2 = " << var2 << endl;
fun(var1,var2);
cout << "After:" << "var1 = " << var1 << '\t' << "var2 = " << var2 << endl;
cout << endl;
//string
string str1 = "hello", str2 = "world";
cout << "Before:" << "str1 = " << str1 << '\t' << "str2 = " << str2 << endl;
fun(str1,str2);
cout << "After:" << "str1 = " << str1 << '\t' << "str2 = " << str2 << endl;
return 0;
}
运行效果: