一、myArray.hpp
#pragma once
#include<iostream>
using namespace std;
template<class T>
class MyArray
{
public:
MyArray(int cap)
{
this->m_Cap = cap;
this->m_Size = 0;
this->pAddress = new T[this->m_Cap];
}
MyArray(const MyArray& arr)
{
this->m_Cap = arr.m_Cap;
this->m_Size = arr.m_Size;
this->pAddress = new T[arr.m_Cap];
for (int i = 0; i < m_Size; i++)
{
this->pAddress[i] = arr.pAddress[i];
}
}
MyArray& operator=(const MyArray& arr)
{
if (this->pAddress != nullptr)
{
delete[] this->pAddress;
this->pAddress = nullptr;
}
this->m_Cap = arr.m_Cap;
this->m_Size = arr.m_Size;
this->pAddress = new T[arr.m_Cap];
for (int i = 0; i < m_Size; i++)
{
this->pAddress[i] = arr.pAddress[i];
}
return *this;
}
T& operator[](int pos)
{
return this->pAddress[pos];
}
void push_Back(const T& val)
{
if (this->m_Cap <= this->m_Size)
{
return;
}
this->pAddress[this->m_Size] = val;
this->m_Size++;
}
int getCap()
{
return this->m_Cap;
}
int getSize()
{
return this->m_Size;
}
~MyArray()
{
if (this->pAddress != nullptr)
{
delete[] this->pAddress;
this->pAddress = nullptr;
}
}
private:
T* pAddress;
int m_Cap;
int m_Size;
};
二、测试用例
主要做了int和Person类型的数组测试
#include<iostream>
#include"myArray.hpp"
using namespace std;
class Person
{
public:
Person() {}
Person(string name, int age)
{
this->m_Name = name;
this->age = age;
}
string m_Name;
int age;
};
int main() {
MyArray<int> iarr(10);
for (int i = 0; i < 10; i++)
{
iarr.push_Back(i + 100);
}
for (int i = 0; i < iarr.getSize(); i++)
{
cout << iarr[i] << " ";
}
cout << endl<<endl;
MyArray<Person> parr(10);
Person p1("aaa", 10);
Person p2("bbb", 20);
Person p3("ccc", 30);
Person p4("ddd", 40);
Person p5("eee", 50);
parr.push_Back(p1);
parr.push_Back(p2);
parr.push_Back(p3);
parr.push_Back(p4);
parr.push_Back(p5);
for (int i = 0; i < parr.getSize(); i++)
{
cout << "姓名: " << parr[i].m_Name << " 年龄: " << parr[i].age << endl;
}
return 0;
}
总结
今天给大家介绍了C++类模板的使用,代码如有错误,欢迎指正。
|