目录
程序示例:
//twotemps.cpp -- 使用重载模板
#include<iostream>
template <typename T>
void Swap(T &a, T &b);
template <typename T>
void Swap(T *a, T *b, int n);
void Show(int a[]);
const int Lim = 8;
int main()
{
using namespace std;
int i = 10;
int j = 20;
cout << "i, j = " << i << ", " << j << ".\n";
cout << "使用 int 的 Swapper: \n";
Swap(i, j);
cout << "Now i, j = " << i << ", " << j << ".\n\n";
int d1[Lim] = { 0, 7, 0, 4, 1, 7, 7, 6 };
int d2[Lim] = { 1, 2, 3, 4, 5, 6, 7, 8 };
cout << "原始数组:\n";
Show(d1);
Show(d2);
Swap(d1, d2, Lim);//匹配重载的另一个
cout << "Swapped arrays:\n";
Show(d1);
Show(d2);
return 0;
}
template <typename T>
void Swap(T &a, T &b)
{
T temp;
temp = a;
a = b;
b = temp;
}
template <typename T>
void Swap(T a[], T b[], int n)
{
T temp;
for (int i = 0; i < n; i++)
{
temp = a[i];
a[i] = b[i];
b[i] = temp;
}
}
void Show(int a[])
{
using namespace std;
cout << a[0] << a[1] << "/";
cout << a[2] << a[3] << "/";
for (int i = 4; i < Lim; i++)
{
cout << a[i] ;
}
cout << endl;
}
运行结果:
(8.12程序)