模板案例-数组封装


一、myArray.hpp

#pragma once
#include<iostream>

using namespace std;

template<class T>
class MyArray
{
public:
	//MyArray(){}

	MyArray(int cap)
	{
		this->m_Cap = cap;
		this->m_Size = 0;
		this->pAddress = new T[this->m_Cap];
	}

	//拷贝构造
	MyArray(const MyArray& arr)
	{
		this->m_Cap = arr.m_Cap;
		this->m_Size = arr.m_Size;

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

	}

	MyArray& operator=(const MyArray& arr)
	{
		if (this->pAddress != nullptr)
		{
			delete[] this->pAddress;
			this->pAddress = nullptr;
		}

		this->m_Cap = arr.m_Cap;
		this->m_Size = arr.m_Size;

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

		return *this;
	}

	T& operator[](int pos)
	{
		return this->pAddress[pos];
	}

	//尾插
	void push_Back(const T& val)
	{
		if (this->m_Cap <= this->m_Size)
		{
			return;
		}

		this->pAddress[this->m_Size] = val;
		this->m_Size++;
	}

	//获取容量
	int getCap()
	{
		return this->m_Cap;
	}

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

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

private:

	T*	 pAddress;	//指向堆区的数组指针
	int  m_Cap;		//数组容量
	int  m_Size;	//数组大小

};

二、测试用例

主要做了int和Person类型的数组测试

#include<iostream>
#include"myArray.hpp"
using namespace std;

class Person
{
public:
	Person() {}

	Person(string name, int age)
	{
		this->m_Name = name;
		this->age = age;
	}


	string m_Name;
	int age;

};


//
int main() {

	MyArray<int> iarr(10);
	for (int i = 0; i < 10; i++)
	{
		iarr.push_Back(i + 100);
	}

	for (int i = 0; i < iarr.getSize(); i++)
	{
		cout << iarr[i] << "  ";
	}
	cout << endl<<endl;

	MyArray<Person> parr(10);
	//Person ps[100];
	Person p1("aaa", 10);
	Person p2("bbb", 20);
	Person p3("ccc", 30);
	Person p4("ddd", 40);
	Person p5("eee", 50);

	parr.push_Back(p1);
	parr.push_Back(p2);
	parr.push_Back(p3);
	parr.push_Back(p4);
	parr.push_Back(p5);

	for (int i = 0; i < parr.getSize(); i++)
	{
		cout << "姓名: " << parr[i].m_Name << " 年龄: " << parr[i].age << endl;
	}

	return 0;
}

总结

今天给大家介绍了C++类模板的使用,代码如有错误,欢迎指正。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值