函数重载:
#include <iostream>
using namespace std;
void swap(int &x, int &y)
{
int tmp = x;
x = y;
y = tmp;
}
void swap(float &x, float &y)
{
float tmp = x;
x = y;
y = tmp;
}
void swap(double &x, double &y)
{
double tmp = x;
x = y;
y = tmp;
}
int main()
{
int a = 1;
int b = 2;
swap(a, b);
cout << a << endl << b << endl;
float s = 3.3;
float t = 4.4;
swap(s, t);
cout << s << endl << t << endl;
double x = 5.5;
double y = 6.6;
swap(x, y);
cout << x << endl << y << endl;
return 0;
}
上面的程序,有明显重复的部分,那么,可不可以用int, float和double抽象出来呢?可以的!如下(这个程序有一点点问题):
#include <iostream>
using namespace std;
template <typename T>
void swap(T &x, T &y)
{
T tmp = x;
x = y;
y = tmp;
}
int main()
{
int a = 1;
int b = 2;
swap(a, b);
cout << a << endl << b << endl;
float s = 3.3;
float t = 4.4;
swap(s, t);
cout << s << endl << t << endl;
double x = 5.5;
double y = 6.6;
swap(x, y);
cout << x << endl << y << endl;
return 0;
}
运行一下上面这个程序,发现有错,为什么呢?百思不得其解,查百度吧!找到原因了:这个swap和STL的swap重名了。故改为如下正确程序:
#include <iostream>
using namespace std;
template <typename T>
void mySwap(T &x, T &y)
{
T tmp = x;
x = y;
y = tmp;
}
int main()
{
int a = 1;
int b = 2;
mySwap(a, b);
cout << a << endl << b << endl;
float s = 3.3;
float t = 4.4;
mySwap(s, t);
cout << s << endl << t << endl;
double x = 5.5;
double y = 6.6;
mySwap(x, y);
cout << x << endl << y << endl;
return 0;
}
至于编译器是如何实现函数模板的,请查看相关书籍。