template<class T> 定义一个模板类
注意模板类看作一个数据类型(int, float)
class A
{
public:
A();
T getlist(T x,int n);
private:
T data[maxsize];
}//构造一个类
下面写main 主函数测试
模板类对象:
A<int>a();//int 可以为其他的数据类型 a 为构造的模板类的对象
注意:一些数据类型为简单数据类型时可用cout显示
但是一些构造类型,则需要调用其相应的显示函数
#include <iostream>
using namespace std;
const int MAXSIZE = 1000;
template<class T>
class Seqlist
{
public:
Seqlist() { length = 0; }
Seqlist(const T a[], int n);
int locate(T x);
T get(int i);//获取第i个位置元素
private:
T data[MAXSIZE];
int length;
};
template<class T>
Seqlist<T>::Seqlist(const T a[], int n)
{
if (n > MAXSIZE)throw"数组长度超过最大长度";
for (int i = 0; i < n; i++)
{
data[i] = a[i];
}
length = n;
}
template<class T>
T Seqlist<T>::get(int i)
{
if (i<1 || i>length)throw"位置非法";
return data[i - 1];
}
template<class T>
int Seqlist<T>::locate(const T x)
{
for (int i = 0; i < length; i++)
if (x == data[i])
return i + 1;
return 0;//查找失败
}
int main()//实例化
{
int a[7] = { 1,2,3,4,5,6,7 };
Seqlist<int>list(a, 7);
int v = list.locate(5);
cout << v << endl;
int d = list.get(5);
cout << d << endl;
}