Caso de plantilla de clase [C ++]

Descripción del caso: para implementar una clase de matriz general, los requisitos son los siguientes:

  1. Puede almacenar datos de tipos de datos integrados y tipos de datos personalizados
  2. Almacene los datos en la matriz en el área del montón
  3. La capacidad de la matriz se puede pasar al constructor.
  4. Proporcione el constructor de copia y el operador correspondientes = para evitar problemas de copia superficial
  5. Proporcione métodos de interpolación de cola y eliminación de cola para agregar y eliminar datos en la matriz
  6. Puede acceder a los elementos de la matriz subindicando
  7. Puede obtener el número actual de elementos en la matriz y la capacidad de la matriz

MyArray.hpp

//自己的通用的数组类
#pragma once
#include <iostream>
#include <string>
using namespace std;


template<class T>
class MyArray
{
public:
	//1、有参构造函数
	MyArray(int capacity)//:m_Capacity(capacity),m_Size(0),pAddress(new T[m_Capacity])
	{
		//cout << "MyArry的有参构造调用" << endl;
		
		this->m_Capacity = capacity;
		this->m_Size = 0;
		this->pAddress = new T[m_Capacity];
		
	}

	//2、拷贝构造函数
	MyArray(const MyArray& arr)
	{
		//编译器提供的拷贝构造函数如下【浅拷贝】
		/*
		this->m_Capacity = arr.m_Capacity;
		this->m_Size = arr.m_Size;
		this->pAddress = arr.pAddress;
		*/
		//cout << "MyArry的拷贝构造调用" << endl;

		//深拷贝
		this->m_Capacity = arr.m_Capacity;
		this->m_Size = arr.m_Size;
		this->pAddress = new T[arr.m_Capacity];
	
		//将arr中的数据拷贝过来
		for (int i = 0; i < m_Size; i++)
		{
			this->pAddress[i] = arr.pAddress[i];
		}
	}

	//3、operator防止浅拷贝
	MyArray& operator=(const MyArray& arr)
	{
		//cout << "MyArry的operator=调用" << endl;

		//先判断原理堆区是否有数据,如果有先释放
		if (this->pAddress != NULL)
		{
			delete[]this->pAddress;
			this->pAddress = NULL;
			this->m_Capacity = 0;
			this->m_Size = 0;
		}

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

	//4、尾插法
	void pushBack(const T& val)
	{
		//先判断容量是否等于大小
		if (this->m_Capacity == this->m_Size)
		{
			cout << "数组大小已满" << endl;
			return;
		}
		this->pAddress[this->m_Size] = val;     //在数组的末尾插入数据
		this->m_Size++;                         //更新数组大小
	}

	//5、尾删法
	void popBack()
	{
		//让用户访问不到最后一个元素,即尾删,逻辑删除
		if (this->m_Size == 0)
		{
			cout << "数组中没有数据" << endl;
			return;
		}
		this->m_Size--;    //逻辑上的尾删
	}

	//6、让用户通过下标的方式访问数据,如果函数调用还想作为左值,则加个&
	//重载[]
	T& operator[](int index)
	{
		return this->pAddress[index];
	}

	//7、返回数组的容量
	int getCapacity()
	{
		return this->m_Capacity;
	}

	//8、返回数组大小
	int getSize()
	{
		return this->m_Size;
	}

	
	//9、打印数组中的普通类型数据
	void printData()
	{
		for (int i = 0; i < this->m_Size; i++)
		{
			cout << this->pAddress[i] << "   ";
		}
		cout << endl;
	}
	

	//析构函数
	~MyArray()
	{
		if (this->pAddress != NULL)
		{
			//cout << "MyArry的析构函数调用" << endl;
			delete[]this->pAddress;
			this->pAddress = NULL;
			this->m_Capacity = 0;
			this->m_Size = 0;
		}
	}

private:
	T* pAddress;      //指针指向堆区开辟的真实数组
	int m_Capacity;   //数组容量
	int m_Size;       //数组大小

};

Lo que necesita atención aquí es el constructor de copia, el operador para evitar la copia superficial y la sobrecarga []

Plantilla de clase case-Array class encapsulation.cpp

#include "MyArray.hpp"
using namespace std;

/*
void printData(MyArray<int>& arr)
{
	for (int i = 0; i < arr.getSize(); i++)
	{
		cout << arr[i] << endl;
	}
}
*/
void test09()
{
	MyArray<int> arr1(5);    //测试有参构造和析构函数

	for (int i = 0; i < 5; i++)
	{
		arr1.pushBack(i);        //利用尾插法向数组加入数据
	}

	cout << "arr1的打印输出:"<< endl;
	arr1.printData();             //打印数据

	cout << "arr1的大小:" << arr1.getSize() << endl;
	cout << "arr1的容量:" << arr1.getCapacity() << endl;

	MyArray<int>arr2(arr1);
	arr2.printData();
	arr2.popBack();              //尾删法
	arr2.printData();
	cout << "arr2的大小:" << arr2.getSize() << endl;
	cout << "arr2的容量:" << arr2.getCapacity() << endl;

}


//测试自定义的数据类型
class Person9
{
public:
	//默认构造
	Person9()
	{}

	//有参构造
	Person9(string name,int age):m_Name(name),m_Age(age)
	{}
	string m_Name;
	int m_Age;
};

//打印数组中的引用数据类型
void printPersonArray(MyArray<Person9>& arr)
{
	for (int i = 0; i < arr.getSize(); i++)
	{
		cout << "姓名:" << arr[i].m_Name << "\t" << arr[i].m_Age << endl;
	}
}

void test009()
{
	MyArray<Person9>arr(10);
	Person9 p1("孙悟空", 99);
	Person9 p2("韩信", 30);
	Person9 p3("猪八戒", 98);
	Person9 p4("张飞", 45);
	Person9 p5("武松", 34);

	//将数据加入到数组中
	arr.pushBack(p1);
	arr.pushBack(p2);
	arr.pushBack(p3);
	arr.pushBack(p4);
	arr.pushBack(p5);

	//打印
	printPersonArray(arr);
	cout << "arr的大小:" << arr.getSize() << endl;
	cout << "arr的容量:" << arr.getCapacity() << endl;


	//尾删法
	arr.popBack();
	//打印
	printPersonArray(arr);
	cout << "arr的大小:" << arr.getSize() << endl;
	cout << "arr的容量:" << arr.getCapacity() << endl;


}
int main(void)
{
	//test09();
	test009();
	system("pause");
	return 0;
}

El resultado de test09 ()

El resultado de test009 ()

Supongo que te gusta

Origin blog.csdn.net/Zhouzi_heng/article/details/115005257
Recomendado
Clasificación