1:群体数据
自定义类型的数据由多个基本类型或者自定义类型的元素所组成,被称为群体数据。
2:参数化多态
将程序所处理的对象的类型参数化,使得一段程序可以用于处理多种不同类型的对象。模板就是C++支持参数化多态的工具。
3:函数模板
定义形式
template <class T> 或者 template <typename T>
类型名 函数名(参数表)
{函数体的定义}
实例程序template1.c
#include <iostream>
#define N 5
using namespace std;
template <class T>
void
outputArray(T *p_array, int count);
int main() {
int a[] = {1,2,3,4,5};
float b[] = {1.1, 2.1, 3.1, 4.1, 5.1};
char c[] = "hello world";
outputArray(a, N);
outputArray(b, N);
outputArray(c, N);
}
// template is needed
template <class T>
void
outputArray(T *p_array, int count) {
for (int i = 0; i < count; i ++) {
cout<<p_array[i]<<" ";
}
cout<<endl;
}
4:类模板
使用类模板用户可以为类声明一种模式,使得类中的某些数据成员,某些成员函数的参数,某些成员函数的返回值能取任何类型。
4.1类模板声明
template <模板参数表>
class 类名
{类成员声明}
4.2如果需要在类外定义其他成员函数
template <模板参数表>
类型名 类名<T>::函数名(参数表)
4.3使用一个模板类来建立对象
模板<模板参数表> 对象名1,对象名2…;
实例程序template2.c
#include <iostream>
// cstdlib == stdlib.h
#include <cstdlib>
using namespace std;
template <class T>
class Store{
private:
T item;
int haveValue;
public:
Store(void);
T GetElem(void);
void PutElem(T x);
};
template <class T>
Store<T>::Store():haveValue(0){}
template <class T>
T Store<T>::GetElem(void) {
if (haveValue == 0) {
cout<<"no item"<<endl;
exit(1);
}
if (haveValue < 0) {
cout<<"no item"<<endl;
haveValue = 0;
exit(1);
}
return item;
}
template <class T>
void Store<T>::PutElem(T x) {
haveValue = 1;
item = x;
}
int main() {
Store<int> s1;
Store<double> s2;
// u will get 3 not 3.3
s1.PutElem(3.3);
int a = s1.GetElem();
cout<<a<<endl;
s2.PutElem(5);
double b = s2.GetElem();
cout<<b<<endl;
}