利用《模板类》构造自己的数据类型容器
#pragma once
#include <iostream>
#include <string>
using namespace std;
template<class T>
class MyArray
{
public:
MyArray(int capacity)
{
this->array_capacity_= capacity;
this->array_num_= 0;
this->array_= new T[this->array_capacity_];
}
~MyArray()
{
if(this->array_ != NULL)
{
delete[] this->array_;
this->array_= NULL;
this->array_capacity_= 0;
this->array_num_= 0;
}
}
MyArray(const MyArray& arr)
{
this->array_capacity_= arr.array_capacity_;
this->array_num_= arr.array_num_;
this->array_= new T[arr.array_capacity_];
for(int i= 0; i<this->array_num_; i++)
{
this->array_[i]= arr.array_[i];
}
}
MyArray& operator= (const MyArray& arr)
{
if(this->array_ != NULL)
{
delete[] this->array_;
this->array_= NULL;
this->array_num_= 0;
this->array_capacity_= 0;
}
this->array_capacity_= arr.array_capacity_;
this->array_num_= arr.array_num_;
this->array_= new T[arr.array_capacity_];
for(int i= 0; i<this->array_num_; i++)
{
this->array_[i]= arr.array_[i];
}
return *this;
}
void pushBack(const T &val)
{
if(this->array_capacity_== this->array_num_)
{
return;
}
this->array_[this->array_num_]= val;
this->array_num_++;
}
void popBack(const T &val)
{
if(this->array_num_ == 0)
{
return;
}
this->array_num_--;
}
T& operator[] (const int index)
{
return this->array_[index];
}
int getNum()
{
return this->array_num_;
}
int getCap()
{
return this->array_capacity_;
}
private:
T *array_;
int array_capacity_;
int array_num_;
};