数组类的封装(泛型编程)

本文探讨了如何使用泛型编程来提高代码的适用性,以数组类封装为例,展示了如何通过template关键字创建类模板,避免重载多个函数。通过这种方式,只需要一个函数即可处理不同类型的数据相加操作。
摘要由CSDN通过智能技术生成

形式:template< class T>或者template< typename T>

这个是提高代码的适用性,比如两个数相加,如果直接用普通函数那么,就要写几个不同参数的重载,如果用泛型编程,只需写一个。

下面是类模板的应用数组类的封装(注意泛型类,直接在头文件实现,不用使用分文件实现,而且文件后缀.h改为.hpp):

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

template< class T>
class MyArray
{
public:


	//构造
	explicit MyArray(int capacity)  //防止隐式类型转换 防止MyArray arr = 10; 写法
	{
		this->m_Capacity = capacity;//容量
		this->m_Size = 0;//插入的位置
		this->pAddress = new T[this->m_Capacity];//整个数组的大小
	}

	MyArray(const MyArray & array)
	{
		this->m_Capacity = array.m_Capacity;
		this->m_Size = array.m_Size;
		this->pAddress = new T[this->m_Capacity];
		for (int i = 0; i < m_Size; i++)
		{
			this->pAddress[i] = array[i];
		}
	}

	~MyArray()
	{
		if (this->pAddress != NULL)
		{
			delete[] this->pAddress;
			this->pAddress = NULL;
		}
	}

	//赋值操作符重载
	MyArray& operator=(MyArray & array)
	{
		//先判断原始数据,有就清空
		if (this->pAddress != NULL)
		{
			delete[] this->pAddress;
			this->pAddress = NULL;
		}

		this->m_Capacity = array.m_Capacity;
		this->m_Size = array.m_Size;
		this->pAddress = new T[this->m_Capacity];
		for (int i = 0; i < m_Size; i++)
		{
			this->pAddress[i] = array[i];
		}
	}

	//[]重载
	//MyArray arr(10);
	//arr[0] = 100;
	T & operator[](int index)
	{
		return this->pAddress[index];
	}

	//尾插法
	void push_Back(T  val)
	{
		this->pAddress[this->m_Size] = val;
		this->m_Size++;
	}


	//获取大小
	int getSize()
	{
		return m_Size;
	}
	//获取容量
	int getCapacity()
	{
		return  this->m_Capacity;
	}


private:
	T * pAddress; //指向堆区指针
	int m_Capacity; //容量
	int m_Size;

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值