3

模板自定义数组

 2 years ago
source link: https://blog.51cto.com/u_15403035/5109810
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

模板自定义数组

原创

无痕恋雪 2022-03-16 16:27:43 ©著作权

文章标签 数组 i++ 数据 文章分类 C/C++ 编程语言 阅读数226

制造通用模板,创建自定义的数组

自定义数组.hpp--文件

#pragma once
#include<iostream>
using namespace std;
#include<string>
template<class T>
class Myarry
{
public:
Myarry() {};//自己创建有参构造,编译器就不提供无参构造,所以必须自己写一次无参构造,即使是空实现也要写!
Myarry(int capacity)//有参构造函数
{
this->capacity = capacity;
this->size = 0;
this->marry = new T[this->capacity];//把数组创建在堆区
}
~Myarry()//析构函数
{
if (this->marry !=NULL)
{
delete []this->marry;//析构数组必须加[],否则会引发断点
marry = NULL;
this->capacity = 0;
this->size = 0;
}
}
Myarry(const Myarry& arr)//拷贝构造
{
this->capacity = arr.capacity;
this->size = arr.size;
this->marry = new T[arr.capacity];
for (int i = 0; i < arr.size; i++)//把数据拷贝过来
{
this->marry[i] = arr->marry[i];
}
}
//等号赋值
Myarry& operator=(const Myarry& arr)
{
if (this->marry != NULL)//如果有数据先清空,再赋值
{
delete[]this->marry;
this->marry = NULL;
this->size = 0;
this->capacity = 0;
}
this->capacity = arr.capacity;
this->size = arr.size;
this->marry = new T[this->capacity];
for (int i = 0; i < this->size; i++)//将数据进行拷贝
{
this->marry[i] = arr.marry[i];
}
return *this;
}
void pushback(const T&ptr)//尾加法
{
if (this->capacity == this->size)
{
cout << "容量已满!" << endl;
return;
}
this->marry[this->size] = ptr;
this->size++;
}
void deleteback()//尾删法
{
if (this->size == 0)
{
cout << "数据为零,没有可删数据!" << endl;
}
delete this->marry[this->size - 1];
this->size--;
}
T & operator[](int index)//通过下标访问数组,并使它作为左值加&
{
if (index > this->capacity)
{
cout << "访问越界!" << endl;
exit(0);
}
return this->marry[index];
}
int gercapacity()//获取数组容量
{
return this->capacity;
}
int getsize()//获取数组元素个数
{
return this->size;
}
private:
T * marry;//数组
int capacity;//数组容量
int size;//数组元素个数
};

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK