C++使用模板对数组进行封装

模板头文件 .hpp

#pragma once
#include<iostream>
#include<string>
using namespace std;

template<class T>
class Myarray
{
public:
	
	explicit Myarray(int spacedate)//explicit 防止隐式类型转换 myarray arr =10;
	{
		this->max =spacedate;
		this->Parray = new T[this->max];
		this->size =0;
	}
	Myarray(const Myarray& art)
	{
		this->Parray= new T[art->max];
		this->size = art.size;
		this->max = art.max;
		for (int i = 0; i < size; i++)
		{
			this->Parray[i] = art.Parray[i];
		}
	}
	~Myarray()
	{
		if(this->Parray != NULL)
		{
			delete[] this->Parray;
			this->Parray = NULL;
		}
	}
	Myarray& operator=(Myarray& p2)//p1=p2
	{
		f(this->Parray != NULL)
		{
			delete[] this->Parray;
			this->Parray = NULL;
		}
		this->Parray= new T[art->max];
		this->size = art.size;
		this->max = art.max;
		for (int i = 0; i < size; i++)
			this->Parray[i] = art.Parray[i];
	}
	//[]重载
	T& operator[](int index)
	{
		return this->Parray[index];
	}
	//插入,尾插法
	void push_back(T val)
	{
		this->Parray[this->size]=val;
		this->size++;
	}
	//获取数组大小
	int getsize()
	{
		return this->size;
	}
	//获取容量
	int getmax()
	{
		return this->max;
	}
private:
	T * Parray;
	int max;//容量
	int size;//当前大小
};

使用头文件对封装后的数组进行操作

#include"ArrayPackage.hpp"
void arrayprint(Myarray<int>& p)
{
	for (int i = 0; i < p.getsize(); i++)
	{
		cout<<p[i]<<"  ";
	}
	cout<<endl;
}
class person
{
public:
	person(){}
	person(string name,int age):tname(name),tage(age){}
	string tname;
	int tage;
};
void arrayprint(Myarray<person>& p)
{
	for (int i = 0; i < p.getsize(); i++)
	{
		cout<<p[i].tname<<"  "<<p[i].tage<<"   ";
	}
	cout<<endl;
}
void test()
{
	Myarray<int>arr(10);
	for(int i=0;i<10;i++)
	{
		arr.push_back(i+10);
	}

	arrayprint(arr);
	person p1("a",10);
	person p2("b",20);
	person p3("c",30);
	person p4("d",40);

	Myarray<person>arr1(10);
	arr1.push_back(p1);
	arr1.push_back(p2);
	arr1.push_back(p3);
	arr1.push_back(p4);

	arrayprint(arr1);
}
void main()
{
	test();
}

实现结果:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值