#include<iostream>
using namespace std;
#include<ctime>
template<class T>
class myarr
{
public:
myarr(int capacity)
{
cout<<"myarr的有参构造!"<<endl;
this->m_capacity=capacity;
this->m_size=0;
this->paddress=new T[this->m_capacity];
}
myarr(const myarr &arr)
{
cout<<"myarr的拷贝构造!"<<endl;
this->m_capacity=arr.m_capacity;
this->m_size=arr.m_size;
this->paddress=new T[arr.m_capacity];//深拷贝
for (int i = 0; i < this->m_size; i++)
{
this->paddress[i]=arr.paddress[i];
}}
myarr& operator=(const myarr &arr)//operator=
{ cout<<"myarr的==构造!"<<endl;
if (this->paddress!=NULL)
{
delete[] this->paddress;
this->paddress=NULL;
this->m_capacity=0;
this->m_size=0;
}
this->m_capacity=arr.m_capacity;
this->m_size=arr.m_size;
this->paddress=new T[arr.m_capacity];
for (int i = 0; i < this->m_size; i++)//深拷贝
{
this->paddress[i]=arr.paddress[i];
}
return *this;
}
void push_back(const T & val)
{
if (this->m_capacity==this->m_size)//判断容量是否等于大小
{
return;
}
this->paddress[this->m_size]=val;//在数组末尾插入数据
this->m_size++; //更新大小
}
void pop_back()
{
if(this->m_size==0)//让用户访问不到最后一个元素,即尾删,逻辑删除
{return;}
this->m_size--;
}
T & operator[](int index)//通过下标访问数组中的元素 arr[0]=100;
{
return this->paddress[index];
}
int getcapacity() //返回容量
{
return this->m_capacity;
}
int getsize() //返回大小
{
return this->m_size;
}
~myarr()
{ cout<<"myarr的西沟!"<<endl;
if (this->paddress!=NULL)
{
delete[] this->paddress;
this->paddress=NULL;
}}
private:
T *paddress;//指针指向堆区开辟的真实数组
int m_capacity;//数组容量
int m_size; //大小
};
void print1(myarr<int> &arr)
{
for (int i = 0; i <arr.getsize(); i++)
{
cout<<arr[i]<<" ";
}
cout<<endl;
}
void test1()//测试1: 测试内置数据类型
{
myarr<int>arr1(5);
for (int i = 0; i < 5; i++)
{
arr1.push_back(i);
}
cout<<"arr1打印输出为:"<<endl;
print1(arr1);
cout<<"arr1的容量和大小为:"<<arr1.getcapacity()<<"\t"<<arr1.getsize()<<endl;
myarr<int> arr2(arr1);
cout<<"arr2打印输出为:"<<endl;
print1(arr2);
arr2.pop_back();
cout<<"arr2尾删后的容量和大小为:"<<arr2.getcapacity()<<"\t"<<arr2.getsize()<<endl;
myarr<int> arr3(100);
arr3=arr1;
}
class person
{
public:
person(){}
person(string name,int age)
{
this->m_name=name;
this->m_age=age;
}
public:
string m_name;
int m_age;
};
void print2(myarr<person> &arr){
for (int i = 0; i < arr.getsize(); i++)
{
cout<<arr[i].m_name<<"\t"<<arr[i].m_age<<endl;
}}
void test2()
{
myarr<person> arr3(10);
string nameseed="0123456789";
for (int i = 0; i < 10; i++)
{
int a=rand()%20+10;
string name="我是";
name+=nameseed[i];
person p(name,a);
arr3.push_back(p);
}
print2(arr3);
cout<<"arr3的容量和大小为:"<<arr3.getcapacity()<<"\t"<<arr3.getsize()<<endl;
}
int main()
{ srand((unsigned int)time (NULL));
test1();
test2();
return 0;
}
黑马C++ 183通用数组类案例 超详细完整记录
最新推荐文章于 2024-05-20 23:52:50 发布