MyList.hpp文件
#pragma once
#include <iostream>
#include <string>
using namespace std;
template<class T>
class MyList
{
public:
MyList(int capacity)
{
cout << "有参构造调用" << endl;
this->m_Capacity = capacity;
this->m_Size = 0;
this->pAddress = new T[this->m_Capacity];
}
MyList(const MyList& arr)
{
cout << "拷贝构造调用" << endl;
this->m_Capacity = arr.m_Capacity;
this->m_Size = arr.m_Size;
this->pAddress = new T[arr.m_Capacity];
for (int i = 0; i < arr.m_Size; i++)
{
this->pAddress[i] = arr.pAddress[i];
}
}
MyList& operator=(const MyList& arr)
{
cout << "operator=调用" << endl;
if (this->pAddress != NULL)
{
delete[] this->pAddress;
this->pAddress = NULL;
this->m_Capacity = 0;
this->m_Size = 0;
}
this->m_Capacity = arr.m_Capacity;
this->m_Size = arr.m_Size;
this->pAddress = new T[arr.m_Capacity];
for (int i = 0; i < arr.m_Size; i++)
{
this->pAddress[i] = arr.pAddress[i];
}
return *this;
}
~MyList()
{
cout << "析构函数调用" << endl;
if (this->pAddress != NULL)
{
delete[] this->pAddress;
this->pAddress = NULL;
}
}
void Push_Back(const T &val)
{
if (this->m_Capacity == this->m_Size)
{
return;
}
this->pAddress[this->m_Size] = val;
this->m_Size++;
}
void Pop_Back()
{
if (this->m_Size == 0)
{
return;
}
this->m_Size--;
}
T& operator[] (int index)
{
return this->pAddress[index]
}
int getCapacity()
{
return this->m_Capacity;
}
int getSize()
{
return this->m_Size;
}
private:
T *pAddress;
int m_Capacity;
int m_Size;
};
测试
#pragma once
#include <iostream>
#include "mList.hpp"
using namespace std;
void printList(MyList<int> &arr)
{
for (int i = 0; i < arr.getSize(); i++)
{
cout << arr[i] << endl;
}
}
void test1()
{
MyList<int> arr1(5);
for (int i = 0; i < 5; i++)
{
arr1.Push_Back(i);
}
printList(arr1);
cout << "arr1的容量:" << arr1.getCapacity() << endl;
cout << "arr1的大小:" << arr1.getSize() << endl;
arr1.Pop_Back();
printList(arr1);
cout << "arr1的容量:" << arr1.getCapacity() << endl;
cout << "arr1的大小:" << arr1.getSize() << endl;
}
int main()
{
test1();
system("pause");
return 0;
}