#include <iostream>
using namespace std;
template<class T>
class MyArray {
friend void test01();//友元函数
public:
MyArray(int capacity)//构造函数
{
this->mCapacity = capacity;
this->mSize = 0;
//申请空间
this->ptr = new T[this->mCapacity];
}
MyArray(const MyArray<T>& another)//拷贝函数
{
this->mCapacity = another.mCapacity;
this->mSize = another.mSize;
//申请空间
this->ptr = new T[this->mCapacity];
//开始拷贝
for (int i = 0; i < this->mSize; i++)
{
this->ptr[i] = another.ptr[i];
}
}
T& operator[](int index)// []操作符重载
{
return this->ptr[index];
}
MyArray<T>& operator=(const MyArray<T>& another)// =操作符重载
{
//原本容器有值
if (this->ptr != nullptr) {
delete[] this->ptr;
this->ptr = nullptr;
this->mCapacity = 0;
this->mSize = 0;
}
this->mCapacity = another.mCapacity;
this->mSize = another.mSize;
this->ptr = new T[this->mCapacity];
for (int i = 0; i < this->mSize; i++)
{
this->ptr[i] = another.ptr[i];
}
return *this;
}
void PushBack(T& data) {//一个&是对左值取引用
//判断容器中是否有位置
if (this->mCapacity <= this->mSize) {
return ;
}
this->ptr[this->mSize] = data;
this->mSize++;
}
void PushBack(T&& data) {//两个&&是对右值取引用
//判断容器中是否有位置
if (this->mCapacity <= this->mSize) {
return ;
}
this->ptr[this->mSize] = data;
this->mSize++;
}
~MyArray() {
if (this->ptr != nullptr) {
delete[] this->ptr;
this->ptr = nullptr;
this->mCapacity = 0;
this->mSize = 0;
}
}
private:
//一共可以存储多少元素
int mCapacity;
//现在有多少元素
int mSize;
//保存数据的首地址
T* ptr;
};
void test01() {
//测试构造函数
MyArray<int> marray(20);
int a = 10, b = 20, c = 30;
//测试数组内添加元素
//对左值取引用
marray.PushBack(a);
marray.PushBack(b);
marray.PushBack(c);
//对右值取引用
marray.PushBack(1);
marray.PushBack(2);
marray.PushBack(3);
//测试[ ]操作符重载
for (int i = 0; i < marray.mSize; i++) {
cout << marray[i] << " ";
}
}
int main() {
test01();
}
STL:模板类手写数组
最新推荐文章于 2024-08-14 17:18:35 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)