#include <iostream>
using namespace std;
template <class T>
class myarray
{
public:
myarray(int capacity)
{
cout << "构造函数" << endl;
m_capacity = capacity;
m_size = 0;
m_paddress = new T[this->m_capacity];
}
myarray(const myarray &array)
{
cout << "拷贝构造" << endl; //深拷贝
this->m_capacity = array.m_capacity;
this->m_size = array.m_size;
m_paddress = new T[this->m->capacity];
for(int i = 0;i < m_size;i++)
{
m_paddress[i] = array[i];
}
}
~myarray()
{
cout << "析构函数" << endl;
if(m_paddress != NULL)
{
delete [] m_paddress;
m_paddress = NULL;
}
}
myarray & operator = (myarray & array) //运算符重载复制拷贝的内容
{
cout << "运算符重载" << endl;
if(m_paddress != NULL) //先判断原来堆区数据是否有数据,有就释放
{
delete [] m_paddress;
m_paddress = NULL;
}
this->m_capacity = array.m_capacity;
this->m_size = array.m_size;
m_paddress = new T[this->m->capacity];
for(int i = 0;i < m_size;i++)
{
m_paddress[i] = array[i];
}
}
T & operator [](int index)
{
return this->m_paddress[index];
}
//尾插
void push_back(T val)
{
m_paddress[this->m_size] = val; //插入元素
this->m_size++; //数组数量更新,增加
}
//尾删
void deleteval(T val)
{
this->m_size--;
}
int getsize() //返回数组大小
{
return m_size;
}
int getcapacity() //返回容量大小
{
return m_capacity;
}
void showinfo()
{
for(int i=0;i<this->m_size;i++)
{
cout << m_paddress[i] << endl;
}
}
private:
int m_capacity;
int m_size;
int *m_paddress;
};
#if 0
void intinfoarray(myarray<int> &array)
{
for(int i =0;i< array.getsize();i++)
{
cout << array[i] << endl;
}
}
class person
{
public:
person()
{
}
person(string name,int age)
{
p_name = name;
p_age = age;
}
void personinfo(myarray<person> & array)
{
for(int i=0;i<array.getsize();i++)
{
cout <<"name: " << array[i].p_name << " age: " << array[i].p_age << endl;
}
}
string p_name;
int p_age;
};
#endif
void test1()
{
//myarray<float>p(5);
myarray<int>p(5);
for(int i=0;i< p.getcapacity();i++)
{
p.push_back(i);
}
p.showinfo();
cout << "size = " << p.getsize() << endl;
cout << "capacity = " << p.getcapacity() << endl;
p.deleteval(5);
p.deleteval(4);
p.showinfo();
cout << "size: " << p.getsize() << endl;
cout << "capacity: " << p.getcapacity() << endl;
}
int main(int argc, char *argv[])
{
test1();
return 0;
}