#include<iostream>
using namespace std;
//函数模板的重载
template <class T>void Swap(T &a, T&b);
template <typename T> void Swap(T a[], T b[], int len);
void printArray(int arr[],int len);
int main()
{
int m = 10, n = 90;
Swap(m, n);
cout << "m = "<< m << ",n = " << n << endl;
//交换两个数组
int a[5] = { 1, 2, 3, 4, 5 };
int b[5] = { 10, 20, 30, 40, 50};
int len = sizeof(a) / sizeof(int);
Swap(a, b, len);
cout << "数组a:" << endl;
printArray(a,len);
cout << "数组b:" << endl;
printArray(b, len);
return 0;
}
template <class T> void Swap(T &a,T &b)
{
T temp = a;
a = b;
b = temp;
}
template<typename T> void Swap(T a[],T b[],int len)
{
T tmp;
for (int i = 0; i < len;i++){
tmp = a[i];
a[i] = b[i];
b[i] = tmp;
}
}
void printArray(int arr[],int len)
{
for (int i = 0; i < len; i++){
if (i == len-1){
cout << arr[i] << endl;
}
else{
cout << arr[i] << " ";
}
}
}
c++——函数模板重载
最新推荐文章于 2025-04-29 21:53:03 发布