C++-------模板类案例:利用类模板写一个数组类

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/XUCHEN1230/article/details/86419901
#pragma once
#include <iostream>
#include <string>

using namespace std;

template<class T>
class MyArry
{
public:
	//构造函数:
	explicit MyArry(int capacity)		//防止隐式类型转换,避免:MyArry arr =10 ;这种写法;
	{
		this->m_Capacity = capacity;
		this->m_Size = 0;
		this->Address = new T[this->m_Capacity];
	}
	//拷贝构造:
	MyArry(const MyArry & arry)
	{
		this->m_Capacity = arry.m_Capacity;
		this->m_Size = arry.m_Size;
		this->Address = new MyArry[this->m_Capacity];
		for (int i = 0; i < arry.m_Size; i++) {
			this->Address[i] = arry[i];
		}
	}
	//析构函数:
	MyArry()
	{
		if (this->Address != NULL) {
			delete[] this->Address;
			this->Address = NULL;
		}
	}
	//重载一个=操作符:
	MyArry & operator =(const MyArry & arr)
	{
		if (this->Address != NULL) {
			delete[] this->Address;
			this->Address = NULL;
		}
		this->m_Capacity = arr.m_Capacity;
		this->m_Size = arr.m_Size;
		this->Address = new MyArry[this->m_Capacity];
		for (int i = 0; i < arr.m_Size; i++) {
			this->Address[i] = arr[i];
		}
	}
	//重载一个[]用于索引:
	T & operator[](int index)
	{
		return this->Address[index];
	}
	//尾插法:
	void push_Back(T  val)
	{
		this->Address[this->m_Size] = val;
		this->m_Size++;
	}
	//获取大小:
	int getSize(MyArry & arr)
	{
		return this->m_Size;
	}
	//获取容量:
	int getCapacity(MyArry & arr)
	{
		return this->m_Capacity;
	}
private:
	T * Address;		//指向堆区空间;
	int m_Capacity;		//容量大小;
	int m_Size;			//大小;
};

main.cpp:

// 19_1_13_study.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include "pch.h"
#include "MyArry.hpp"
#include <iostream>
#include <string>

using namespace std;

//输出int型数组的方法:
void printIntArry(MyArry<int> & arr)
{
	int i = 0;
	for (i; i < arr.getSize(arr); i++) {
		cout << arr[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 printPersonArry(MyArry<Person> & arry)
{
	int i = 0;
	for (i; i < arry.getSize(arry); i++) {
		cout << "姓名:"<<arry[i].m_Name<<" 年龄:"<<arry[i].m_Age << endl;
	}
}


int main()
{
	MyArry<int> arry(10);
	for (int i = 0; i < 10; i++) {
		arry.push_Back(i);
	}
	printIntArry(arry);

	Person p1("asdasd", 123);
	Person p2("sd", 12343);
	Person p3("asdasdfsd", 23423);
	Person p4("asfdsad", 23423);

	MyArry<Person> pArry(4);
	//自定义的默认Person类型的数组的时候,一定会调用Person的默认构造的;
	pArry.push_Back(p1);
	pArry.push_Back(p2);
	pArry.push_Back(p3);
	pArry.push_Back(p4);

	printPersonArry(pArry);

	return 0;
}



模板类

猜你喜欢

转载自blog.csdn.net/XUCHEN1230/article/details/86419901