函数模版
功能相同,类型不同
templeate<模版参数表>
类型名 函数名(参数表)
{
函数的定义
}
#include <iostream>
using namespace std;
template <typename myT>
myT mymin(myT a, myT b)
{
return a < b ? a : b;
}
int main()
{
int a = 2,b = 3;
cout << mymin(a, b);
}
类模版
template<模板参数表>
class 类名
{
类成员声明
}
//类成员声明的方法与普通类的定义相同,若要在类模版外定义其成员函数,需采用以下方式:
template<模版参数表>
类型名 类名<模板参数标识符列表>::函数名(参数表)
//使用模板类来建立对象时,应按如下形式声明:
模板名<模板参数标识符列表>对象名1,...,对象名n;
#include <iostream>
using namespace std;
template <class myT> //类模版,实现对任意类型的数据进行存储
class myArray
{
private:
myT* items;
int size;
public:
myArray(myT arr[], int s); //构造函数
void print();
};
template<typename myT>
myArray<myT>::myArray(myT arr[],int s)
{
items = new myT[s];
size = s;
for (int i = 0; i < s; i++)
items[i] = arr[i];
}
template<typename myT>//类模版外定义成员函数
void myArray<myT>::print()
{
for (int i = 0; i < size; i++)
cout << " " << items[i];
}
int main()
{
int a[]= { 1,2, 3, 4, 5 };
char b[] = { 'a', 'b', 'c', 'd' };
myArray<int> intArr(a, 5);
intArr.print();
cout << endl;
myArray<char> charArr(b, 4);
charArr.print();
return 0;
}

502

被折叠的 条评论
为什么被折叠?



