注意
- 模板类编程头文件要包含CPP
- 今天头疼 剩下的忘了
头文件
#pragma once
#define _CRT_SECURE_NO_WARNINGS
template <typename T>
class List
{
public:
List(int capacity);
~List();
int getlen();
int getcapacity();
int insert(const T& t,int pos);
T del(int pos);//总结经验,老老实实的返回变量,不要用引用
T get(int pop);
void clear();
private:
int len;
int capacity;
T* array;
};
cpp文件
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include "List.h"
using namespace std;
template <typename T>
List<T>::List(int capacity)
{
len = 0;
array = new T[capacity];
this->capacity = capacity;
}
template <typename T>
List<T>::~List()
{
if (array != NULL)
{
delete[] array;
}
len = 0;
capacity = 0;
cout << "xigou" << endl;
}
template <typename T>
int List<T>::getlen()
{
return len;
}
template <typename T>
int List<T>::getcapacity()
{
return capacity;
}
template <typename T>
int List<T>::insert(const T& t, int pos)
{
int ret=0;
if (len == capacity||pos<0)
{
ret = -1;
cout << "no sapce to insert\n";
return ret;
}
if(pos>len)
{
pos = len;
}
for (int i = len;i > pos;i--)//元素后移
{
array[i] = array[i-1];
}
array[pos] = t;
len++;//记得给长度加1
return ret;
}
template <typename T>
T List<T>::del(int pos)
{
T tmp;
if (pos < 0 || pos >= len)
{
cout << "no array in this position\n";
return array[0];
}
tmp = array[pos];
len--;//长度减少
for (int i = pos;i < len;i++)
{
array[i] = array[i + 1];
}
return tmp;
}
template <typename T>
T List<T>::get(int pos)
{
return array[pos];
}
template <typename T>
void List<T>::clear()
{
memset(array, 0, sizeof(T)*len);
len = 0;
return;
}
测试cpp
void testList()
{
Teacher t1, t2, t3;
t1.age = 31;
strcpy(t1.name, "t1t1t1");
strcpy(t1.worknum, "num1");
t2.age = 32;
strcpy(t2.name, "t2t2t2");
strcpy(t2.worknum, "num2");
t3.age = 33;
strcpy(t3.name, "t3t3t3");
strcpy(t3.worknum, "num3");
List<Teacher> list(5);//类模板的参数 记得<>
list.insert(t3, 2);
list.insert(t2, 0);
list.insert(t1, 0);
cout << list.getlen() << endl;
cout << list.getcapacity() << endl;
Teacher tmp;
for (int i = 0;i < list.getlen();i++)
{
tmp = list.get(i);
cout << tmp.name << endl;
}
tmp=list.del(1);
cout << tmp.name << endl;
list.clear();
}
如果非要把删除的节点用引用返回出去可以
template <typename T>
void List<T>::del(int pos,T& t)//传入接它的变量
{
T tmp;
if (pos < 0 || pos >= len)
{
cout << "no array in this position\n";
return array[0];
}
tmp = array[pos];//改变变量的值 就像指针一样
t=tmp;
len--;//长度减少
for (int i = pos;i < len;i++)
{
array[i] = array[i + 1];
}
return tmp;
}