实现功能:
对于用户提供的数据类型能够实现①整个数组赋值(拷贝)②插入与删除 ③获得数组的大小和容量
头文件 “MyArray.hpp" :
#pragma once
#include<iostream>
using namespace std;
template <class T>
class MyArray
{
public:
MyArray(int capacity)
{
this->m_Capacity = capacity;
this->m_Size = 0;
this->pAddress = new T[capacity];
}
MyArray(const MyArray& arr)
{
this->m_Capacity = arr.m_Capacity;
this->m_Size = arr.m_Size;
this->pAddress = new T[this->m_Capacity];
for (int i = 0; i < this->m_Size; i++)
{
this->pAddress[i] = arr.pAddress[i];
}
}
~MyArray()
{
if (this->pAddress)
{
delete[] this->pAddress;
this->pAddress = NULL;
}
}
MyArray& operator=(const MyArray& arr)
{
if (this->pAddress)
{
delete[] this->pAddress;
this->pAddress = NULL;
}
this->m_Capacity = arr.m_Capacity;
this->m_Size = arr.m_Size;
this->pAddress = new T[this->m_Capacity];
for (int i = 0; i < this->m_Size; i++)
{
this->pAddress[i] = arr.pAddress[i];
}
}
void Push_Back(const T& val)
{
if (this->m_Capacity == this->m_Size)
{
cout << "The Array is full" << endl;
return;
}
this->pAddress[this->m_Size] = val;
this->m_Size++;
}
void Pop_Back()
{
if (this->m_Size)this->m_Size--;
else return;
}
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;
};
主函数测试:
#include<iostream>
#include <string>
using namespace std;
#include"MyArray.hpp"
class Person
{
public:
Person(){}
Person(string name, int age)
{
m_Name = name;
m_Age = age;
}
string m_Name;
int m_Age;
};
void Print( MyArray<Person>& arr)
{
for (int i = 0; i < arr.getSize(); i++)
{
cout << arr[i].m_Name << " " << arr[i].m_Age << endl;
}
}
void test()
{
MyArray<Person> arr(10);
Person p1("Vi", 19);
Person p2("jinx", 16);
Person p3("Caitlyn", 19);
Person p4("Worick", 45);
Person p5("Victor", 25);
arr.Push_Back(p1);
arr.Push_Back(p2);
arr.Push_Back(p3);
arr.Push_Back(p4);
arr.Push_Back(p5);
Print(arr);
cout << "Capacity: " << arr.getCapacity() << endl;
cout << "Size: " << arr.getSize() << endl;
}
int main()
{
test();
system("pause");
return 0;
}