• 类模板应用 – 数组类封装
  • 将类写到 myArray.hpp中
  • 属性:
  • T * pAddress; 指向堆区数组指针
  • int m_Capacity 数组容量
  • int m_Size ;数组大小
  • 行为
  • myArray(int capacity)
  • myArray(const MyArray & arr)
  • operator=
  • operator[]
  • ~myArray()
  • getCapacity
  • getSize
  • pushback

myArray.hpp

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

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

	//有参构造
	MyArray(int capacity)
	{
		this->m_Capacity = capacity;
		this->m_Size = 0;
		this->pAddress = new T[this->m_Capacity];
	}

	//拷贝构造
	MyArray(const MyArray & arr)
	{
		this->m_Capacity = arr.m_Capacity;
		this->m_Size = arr.m_Size;
		this->pAddress = new T[this->m_Capacity];
		for (int i = 0; i < arr.m_Size;i++)
		{
			this->pAddress[i] = arr.pAddress[i];
		}
	}

	//重载=   
	MyArray& operator=( const MyArray & arr)
	{
		if (this->pAddress)
		{
			delete[] this->pAddress;
			this->pAddress = NULL;
		}

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


	//重载[] 
	T& operator[] (int index)
	{
		return this->pAddress[index];
	}

	//尾插法
	void pushBack(const T&val)
	{
		if (this->m_Capacity == this->m_Size)
		{
			return;
		}
		this->pAddress[this->m_Size] = val;
		this->m_Size++;
	}

	//获取数组容量
	int getCapacity()
	{
		return this->m_Capacity;
	}

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

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

private:
	T * pAddress; //指向堆区真实数组指针

	int m_Capacity; //数组容量

	int m_Size;  //数组大小

};

类模板应用-数组类封装.cpp

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

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

	string m_Name;
	int m_Age;
};

void myPrintInt(MyArray <int> &myIntArr)
{

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

void test01()
{
	MyArray <int> myIntArr(100);
	for (int i = 0; i < 10;i++)
	{
		myIntArr.pushBack(i + 100);
	}
	myPrintInt(myIntArr);

}

void myPrintPerson(MyArray<Person> &myPersonArr)
{
	for (int i = 0; i < myPersonArr.getSize();i++)
	{
		cout << "姓名: " << myPersonArr[i].m_Name << " 年龄:" << myPersonArr[i].m_Age << endl;
	}
}

void test02()
{
	MyArray<Person> myPersonArr(100);
	Person p1("孙悟空", 1000);
	Person p2("猪八戒", 800);
	Person p3("唐僧", 500);
	Person p4("沙悟净", 300);
	Person p5("白龙马", 10000);

	myPersonArr.pushBack(p1);
	myPersonArr.pushBack(p2);
	myPersonArr.pushBack(p3);
	myPersonArr.pushBack(p4);
	myPersonArr.pushBack(p5);

	myPrintPerson(myPersonArr);

	cout << "数组容量: " << myPersonArr.getCapacity() << endl;
	cout << "数组大小: " << myPersonArr.getSize() << endl;
}

int main(){

//	test01();
	test02();

	system("pause");
	return EXIT_SUCCESS;
}