模板自定义数组

Posted 无痕恋雪

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了模板自定义数组相关的知识,希望对你有一定的参考价值。

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

自定义数组.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;//数组元素个数
;

测试文件

#include "自定义数组.hpp"
class person

public:
person()

this->age = 0;

int age;
string name;
;
void text01()

person p[4];
p[0].age = 20;
p[0].name = "张三";
p[1].age = 0;
p[1].name = "李四";
p[2].age = 40;
p[2].name = "王五";
p[3].age = 80;
p[3].name = "赵六";
Myarry<person>pp(10);
for (int i = 0; i < 4; i++)

pp.pushback(p[i]);

for (int i = 0; i < pp.getsize(); i++)

cout << pp[i].name<<pp[i].age<< endl;


void text02()

Myarry<int>inta(10);
for (int i = 0; i < 5; i++)

inta.pushback(i);

for (int i = 0; i < inta.getsize(); i++)

cout << inta[i] << endl;


int main()

/*text02();*/
text01();
return 0;

以上是关于模板自定义数组的主要内容,如果未能解决你的问题,请参考以下文章

如何使用自定义值初始化模板类中的数组?

以变​​量为参数的 django 自定义模板过滤器

JSON自定义排序

sql 自定义排序

sql server自定义排序

C# 等号右箭头表示啥