C++数组类封装 模板案例

学完模板,实践操作

数组类的封装.cpp

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

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

	string name;
	int age;
};

void printff(MyArray<p> &arr) {
	for (int i = 0; i < arr.GetSize(); i++) {
		cout << "姓名:" << arr[i].name << ' ' << "年龄:" << arr[i].age << endl;
	}
}
//测试自定义类型
void test1() {
	MyArray<p>arr(10);
	p p1("刘备", 27);
	p p2("张飞",23);
	p p3("关羽", 24);
	p p4("孙权", 20);
	p p5("司马懿", 21);
	p p6("曹操", 22);
	arr.Push_Back(p1);
	arr.Push_Back(p2);
	arr.Push_Back(p3);
	arr.Push_Back(p4);
	arr.Push_Back(p5);
	arr.Push_Back(p6);
	printff(arr);
	cout << arr.GetSize() << endl;
	cout << arr.Getcity() << endl;
}

int main() {
	test1();
}

MyArray.hpp

#pragma once
#include<iostream>
#include<cstring>
using namespace std;

template<class T>
class MyArray
{
public:
	MyArray(int capacity)//有参构造
	{
		this->m_city = capacity;
		this->size = 0;
		this->len = new T[m_city];
	}

	MyArray(const MyArray& arr)//拷贝构造
	{
		this->m_city = arr.m_city;
		this->size = arr.size;
		//this->len = arr.len 浅拷贝

		this->len = new T[arr.size];//深拷贝

		//将arr中的数据进行拷贝
		for (int i = 0; i < size; i++)
		{
			this->len[i] = arr.len[i];
		}

	}



	//operator= 防止浅拷贝
	MyArray& operator=(const MyArray& arr)
	{
		//先判断原堆区是否有数据,先释放
		if (this->len != NULL)
		{
			delete[] this->len;
			this->len = NULL;
			this->m_city = 0;
			this->size = 0;
		}

		this->m_city = arr.m_city;
		this->size = arr.size;
		this->len = new T[arr.m_city];
		//将arr中的数据进行拷贝
		for (int i = 0; i < this->size; i++)
		{
			this->len[i] = arr.len[i];
		}
	}

	//尾插法
	void Push_Back(const T& val) {
		//判断容量是否等于大小
		if (this->m_city == this->size) {
			cout << "容量已满";
			return;
		}

		this->len[this->size] = val;//数组末尾插入数据
		this->size++;//更新数组大小
	}

	//尾删法
	void Pop_Back() {
		if (this->size == 0) {
			cout << "无数据";
			return;
		}
		this->size--;
	}

	//通过下标方式访问数组中的元素,重载[]
	T& operator[](int index) {
		return  this->len[index];
	}

	//返回数组容量
	int Getcity() {
		return this->m_city;
	}

	//返回数组大小
	int GetSize() {
		return this->size;
	}

	~MyArray()//析构函数
	{
		if (this->len != NULL)
		{
			delete[] this->len;
			this->len = NULL;
		}
	}
private:
	T * len;//指针指向堆区指向的真实数组
	int	m_city;//数组容量
	int size;//数组大小
};

对于浅拷贝和深拷贝知识需要再次回顾
在有指针时需要手动写深拷贝

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值