1.模板类的使用
//Array.h
#ifndef ARRAY_H
#define ARRAY_H
template< typename T >
class Array
{
public:
Array(int s);
virtual ~Array();
virtual const T& Entry(int index)const;
virtual void Enter(int index, const T& value);
protected:
int size;
T* element;
};
template
Array
::Array(int s)
{
if (s > 1)
{
size = s;
}
else
{
size = 1;
}
element = new T[size];
}
template
Array
::~Array()
{
delete[] element;
}
template
const T& Array
::Entry(int index)const { return element[index]; } template
void Array
::Enter(int index, const T& value) { element[index] = value; } #endif ARRAY_H
#include
#include "Array.h"
using namespace std;
void main()
{
Array
Intary(5);
int i;
for (i = 0; i < 5; i++)
{
Intary.Enter(i, i);
}
cout << "Integer Array:\n";
for (i = 0; i < 5; i++)
{
cout << Intary.Entry(i) << "\t";
}
cout << "\n";
Array
Douary(5);
for (i = 0; i < 5; i++)
{
Douary.Enter(i, i);
}
cout << "double Array:\n";
for (i = 0; i < 5; i++)
{
cout << Douary.Entry(i) << "\t";
}
cout << endl;
system("pause");
}
3.类模板可以做形参,但实际调用时是模板的实例化对象,拥有类模板参数的函数一定是函数模板
4.类模板可以是基类也可以是派生类
5.派生类模板
//BoundArray.h
#ifndef BOUNDARRAY_H
#define BOUNDARRAY_H
#include "Array.h"
template
class BoundArray : public Array
{
public:
BoundArray(int low = 0, int height = 1);
virtual const T& Entry(int index)const;
virtual void Enter(int index, const T& value);
private:
int min;
};
template
BoundArray
::BoundArray(int low, int height) :Array
(height - low + 1) { min = low; } template
const T& BoundArray
::Entry(int index)const { return Array
::Entry(index - min); } template
void BoundArray
::Enter(int index, const T& value) { Array
::Enter(index - min, value); } #endif BOUNDARRAY_H
7.STL-Standard Template Library-标准模板库,主要组件:容器container、迭代器iterator、算法algorithm
序列容器,提供顺序表的表示和操作
vector向量
deque双向列表
list双向链表
关联容器
set集合
multilist集合
map映射
multimap映射
容器适配器
stack栈,后进先出
queue队列,先进先出
priority_queue优先队列,优先级高的先出