60.模板类-数组封装

main.cpp

#define _CRT_SECURE_NO_WARNINGS
#include
using namespace std;
#include "MyArray.hpp"
#include 

//输出int类型数组
void printIntArray(  MyArray& array)
{
	for (int i = 0; i < array.getSize();i++)
	{
		cout << array[i] << endl;
	}
}

class Person
{
public:
	Person(){};

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



//输出Person类型数组
void printPersonArray( MyArray & array )
{
	for (int  i = 0; i < array.getSize(); i++)
	{
		cout << "姓名: " << array[i].m_Name << " 年龄: " << array[i].m_Age << endl;
	}
}



int main(){

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

	printIntArray(arr);


	Person p1("aaaa", 10);
	Person p2("bbbb", 12);
	Person p3("cccc", 14);
	Person p4("dddd", 15);

	MyArrayarr2(10);
	arr2.push_Back(p1);
	arr2.push_Back(p2);
	arr2.push_Back(p3);
	arr2.push_Back(p4);

	printPersonArray(arr2);
	



	system("pause");
	return EXIT_SUCCESS;
}

头文件MyArray.hpp

#pragma  once 
#include 
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;

};

 

你可能感兴趣的:(C++整理)