这篇文章主要介绍了如何使用c++模板自定义数组,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。
前言:
制造通用模板,创建自定义的数组,
一个数组,里面有这么几个属性,数组容量,数组元素个数,数组本身内存地址,这几个数据都是定义私有类型,提供有参构造,让用户可以构造出这个数组对象。下面是有参构造和拷贝构造和析构函数还有operator=重载的代码
在前面类模板中成员函数创建有这个主意问题,最好的办法就是把类模板写在一个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;
}
感谢你能够认真阅读完这篇文章,希望小编分享的“如何使用c++模板自定义数组”这篇文章对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,更多相关知识等着你来学习!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。