.hpp文件
- #include
- #include
- #include
- using namespace std;
- template <class T>
- class arraylist
- {
- private:
- T* data ;//数组地址
- int size;//长度
- int count;//容量
-
- public:
- arraylist();
- ~arraylist();
- void add(T t);
- T& get(int index);
- int getsize();
- };
- template <class T>
- arraylist
:: arraylist() - {
- this->count = 2;
- this->size = 0;
- this->data = new T[count];
- }
- template <class T>
- arraylist
::~arraylist() - {
- if(data != NULL)
- {
- delete [] data;
- data = NULL;
- }
- }
- template <class T>
- void arraylist
::add(T t) - {
- if(size == count)
- {
- count = count * 2;
- T* newdata = new T[count];
- memcpy(newdata,data,size*sizeof(T));
- delete [] data;
- data = newdata;
- }
- data[size] = t;
- size++;
- }
- template <class T>
- T& arraylist
::get(int index) - {
- return data[index];
- }
-
- template <class T>
- arraylist
::getsize() - {
- return size;
- }
.main文件
- #include
- #include
- #include
- #include "arraylist.hpp"
- using namespace std;
- class person
- {
- private:
- char name[50];
- int age;
- public:
- person(){}
- person(char *name,int age)
- {
-
- strcpy(this->name,name);
- this->age = age;
- }
- char *getname()
- {
- return name;
- }
- void setname(char *name)
- {
- strcpy(this->name,name);
- }
- void showinformation()
- {
- cout << "姓名" << name << "\n年龄" << age <
- }
- };
- void fun01()
- {
- person p1("张三",18);
- person p2("张四",18);
- person p3("张寺",18);
- person p4("张死",18);
- person p5("张斯",18);
- arraylist
ps; - ps.add(p1);
- ps.add(p2);
- ps.add(p3);
- ps.add(p4);
- ps.add(p5);
- int len = ps.getsize();
- cout << "len=" << len << endl;
- for(int i = 0 ;i < len;i++)
- {
- ps.get(i).showinformation();
- }
- }
-
- int main(int argc, char *argv[])
- {
- fun01();
- return 0;
- }
运行结果: