//模板类头文件
#ifndef SELFLIST_H
#define SELFLIST_H
template < class T>
class SelfList{
private:
T* arrayList;
int maxLength;
int currentLength;
int position;
public:
SelfList(const int size);
~SelfList();
void Clear();//清空列表
int Length();//返回当前长度
bool Append(const T value);
bool Insert(const int p, const T value);
bool Delete(const int p);
bool GetValue(const int p, T& value);
bool SetValue(const int p, const T value);
bool GetPos(int &p, const T value);//把值为value的元素位置返回到变量p中
T operator [](int p);
};
template
T SelfList
::operator [](int p)
{
if (p<0 || p>currentLength || currentLength < 0)
return -1;
return arrayList[p];
}
template
SelfList
::SelfList(const int size)
{
maxLength = size;
arrayList = new T[maxLength];
currentLength = 0;
position = 0;
}
template
SelfList
::~SelfList() { delete[] arrayList; arrayList = NULL; } template
void SelfList
::Clear() { delete[] arrayList; position = 0; currentLength = 0; arrayList = new T[maxLength]; } template
int SelfList
::Length() { return currentLength; } template
bool SelfList
::Append(const T value) { if (currentLength >= maxLength) return false; else { arrayList[currentLength] = value; currentLength++; } return true; } template
bool SelfList
::Insert(const int p, const T value) { if (currentLength >= maxLength) return false; if (p<0 || p>currentLength) cout << "the point is illegal" << endl; for (int i = currentLength; i > p; i--) arrayList[i] = arrayList[i - 1]; arrayList[p] = value; currentLength++; return true; } template
bool SelfList
::Delete(const int p) { if (currentLegth <= 0) return false; if (p<0 || p>currentLength - 1) return false; for (int i = p; i < currentLength - 1; i++) arrayList[i] = arrayList[i + 1]; currentLength--; return true; } template
bool SelfList
::GetValue(const int p, T& value) { if (currentLength <= 0) return false; if (p<0 || p>curentLength - 1) return false; value = arrayList[p]; return true; } template
bool SelfList
::SetValue(const int p, const T value) { if (p<0 || p>currentLength - 1) return false; arrayList[p] = value; return true; } template
bool SelfList
::GetPos(int &p, const T value) { int i = 0; for (; i < currentLength; i++) { if (arrayList[i] == value) break; else return false; } p = &arrayList[i]; return true; } #endif //主函数 #include
#include"SelfList.h" using namespace std; int main(int argc, char* argv[]) { SelfList
list(5); for (int i = 0; i < 3; i++) list.Append(i+4); cout << list.Length()<