实现一个通用性数组:
1.可储存不同类型的元素;
2.将数组在堆区开辟;
3.可通过下标访问数组元素;
4.可访问数组大小、元素个数;
5.提供拷贝构造函数防止浅拷贝问题产生;
#include <iostream>
using namespace std;
template<class T>
class Array
{
private:
int size;
int len;
T * arr = NULL;
public:
Array(int size)
{
this-> size = size;
this->len = 0;
arr = new T[this-> size];
}
/*Array(const Array & array)//拷贝构造
{
this->size = array.size;
this->len = array.len;
this->arr = new T[size];
for(int i=0;i<array.len;i++)
{
arr[i] = array.arr[i];
}
}*/
/* Array<T>& operator=(const Array<T>& array)
{
delete [] arr;
this->len = array.len;
this->size = array.size;
arr = new T[array.size];
for(int i = 0;i<len;i++)
{
arr[i] = array.arr[i];
}
return *this;
}*/
void add(const T& NUM)
{
if(this->len == this->size)
{
cout<< "array is full" << endl;
return;
}
arr[this->len++] = NUM;
}
int get_len()
{
return this->len;
}
int get_size()
{
return this->size;
}
T& operator[](int index)
{
return arr[index];
}
~Array()
{
if(this->arr != NULL)
{
delete [] this->arr;
arr = NULL;
}
}
};
template<class T>
ostream& operator<<(ostream &out,Array<T> &array)
{
for(int i = 0; i< array.get_len(); i++)
{
out << array[i] <<" ";
}
out << endl;
return out;
}
void test01()
{
class Array<char> a1(20);
a1.add('a');
a1.add('b');
a1.add('c');
a1.add('d');
a1.add('e');
a1.add('f');
a1.add('g');
cout << a1;
}
int main(int argc, char *argv[])
{
test01();
return 0;
}
[点击并拖拽以移动]