我们常见的类定义方式
class List
{
private:
int list[10];
int len;
public:
.......
};
这种方式有一个缺点就是只能用来实例化int类型的list,要使一个类成为真正的模板,需要一种语言构造,它把int抽象化成ItemType成为一个参数,通过C++的类模板可以实现这一功能。
template <模板形参列表>
模板形参包括:class、typename
template <class ItemType>
class List
{
private:
ItemType list[10];
ItemType len;
public:
.......
};
在实例化的时候我们可以通过传入不同类型(int、float等)来生成不同类型的list对象。
附上写的小栗子:
glist.h
const int MAX_LEN=100;
template<class ItemType>
class Glist
{
private:
int length;
int currentpos;
ItemType list[MAX_LEN];
public:
Glist()
{
length=0;
currentpos=0;
}
void insert(const ItemType & item)
{
if(length>=MAX_LEN)
{
return;
}
list[++length]=item;
}
int getLength()
{
return length;
}
bool isEmpty()
{
return (length==0);
}
bool isFull()
{
return (length==MAX_LEN);
}
void deleteItem(const ItemType & item)
{
int index=0;
while(index<length && list[index]!=item)
{
index++;
}
if(index<length)
{
list[index]=list[length-1];
}
length--;
}
int indexOf(const ItemType & item)
{
int index=0;
while(index<length && list[index]!=item)
{
index++;
}
return (index<length)?index:-1;
}
ItemType getValueByIndex(int index)
{
return list[index];
}
};
testList.cpp
#include <iostream>
#include "glist.h"
using namespace std;
int main()
{
Glist<int> intList;
Glist<char> charList;
intList.insert(3);
intList.insert(5);
charList.insert('s');
charList.insert('c');
cout<<"int list len"<<intList.getLength()<<endl;
cout<<"char list len:"<<charList.getLength()<<endl;
return 0;
}