#include <iostream>
#include <string>
using namespace std;
template <class T>
class ArrayTmp{
public:
ArrayTmp(int capacity )
{
cout<<"构造函数"<<endl;
this->m_Capacity = capacity;
this->m_size = 0;
this->m_pArray = new T[this->m_Capacity];
}
ArrayTmp(ArrayTmp &array)
{
cout<<"拷贝构造函数"<<endl;
this->m_Capacity = array.m_Capacity;
this->m_size = array.m_size;
this->m_pArray = new T[this->m_Capacity];
for(int i = 0; i<this->m_size; i++)
{
this->m_pArray[i] = array.m_pArray[i];
}
}
ArrayTmp& operator=(ArrayTmp &array)
{
cout<<"重载operator=成员函数"<<endl;
if (this->m_pArray != NULL)
{
delete this->m_pArray;
this->m_Capacity = 0;
this->m_size = 0;
}
this->m_Capacity = array.m_Capacity;
this->m_size = array.m_size;
this->m_pArray = new T[this->m_Capacity];
int i= 0;
for(i = 0; i<this->m_size; i++)
{
this->m_pArray[i] = array.m_pArray[i];
}
return *this;
}
T operator[](int index)
{
return this->m_pArray[index];
}
int getCount()
{
return this->m_size;
}
int getCapacity()
{
return this->m_Capacity;
}
void append(const T &item)
{
if (m_size == m_Capacity)
{
cout<<__LINE__<<endl;
T* pArray_tmp = new T[m_Capacity+5];
for (int i=0; i<m_size; i++)
{
pArray_tmp[i] = this->m_pArray[i];
}
delete [] this->m_pArray;
this->m_pArray = pArray_tmp;
this->m_Capacity += 5;
}
this->m_pArray[this->m_size] = item;
this->m_size++;
}
void pop()
{
this->m_size--;
}
~ArrayTmp()
{
if (this->m_pArray != NULL)
{
delete []this->m_pArray;
this->m_pArray = NULL;
}
}
private:
T *m_pArray;
int m_Capacity;
int m_size;
};
void showPrint(ArrayTmp<int> &array)
{
for (int i = 0; i<array.getCount(); i++)
{
cout<<array[i]<<" ";
}
cout<<endl;
}
void test1()
{
ArrayTmp<int> array1(3);
for (int i=0; i<20; i++)
{
array1.append(i);
}
showPrint(array1);
cout<<"mem_count:"<<array1.getCount()<<endl;
cout<<"capacity:"<<array1.getCapacity()<<endl;
ArrayTmp<int> array2(array1);
array2.pop();
showPrint(array2);
cout<<"mem_count:"<<array2.getCount()<<endl;
cout<<"capacity:"<<array2.getCapacity()<<endl;
}
class Person{
public:
Person(){};
Person(string name, int age)
{
this->m_Name = name;
this->m_Age = age;
}
string m_Name;
int m_Age;
};
void showPersonPrint(ArrayTmp<Person> &array)
{
for (int i = 0; i<array.getCount(); i++)
{
cout<<"name:"<<array[i].m_Name<<" "<<"age:"<<array[i].m_Age<<endl;
}
}
void test2()
{
Person per1("张三", 22);
Person per2("李四", 23);
Person per3("王五", 24);
Person per4("赵六", 25);
Person per5("马七", 26);
ArrayTmp<Person> array2(1);
array2.append(per1);
array2.append(per2);
array2.append(per3);
array2.append(per4);
array2.append(per5);
array2.pop();
showPersonPrint(array2);
cout<<"mem_count:"<<array2.getCount()<<endl;
cout<<"capacity:"<<array2.getCapacity()<<endl;
}
int main()
{
test2();
return 0;
}