C++_数组模板封装

案例描述: 实现一个通用的数组类,要求如下:

  • 可以对内置数据类型以及自定义数据类型的数据进行存储

  • 将数组中的数据存储到堆区

  • 构造函数中可以传入数组的容量

  • 提供对应的拷贝构造函数以及operator=防止浅拷贝问题

  • 提供尾插法和尾删法对数组中的数据进行增加和删除

  • 可以通过下标的方式访问数组中的元素

  • 可以获取数组中当前元素个数和数组的容量

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


// 数组类的封装

template<class T>
class myArray
{
public:
	// 构造函数
	myArray(int capacity)
	{
		this->m_capacity = capacity;
		this->m_size = 0;
		this->p_address = new T[m_capacity];
	}

	// 拷贝函数
	myArray(const myArray& arr)
	{
		this->m_capacity = arr.m_capacity;
		this->m_size = arr.m_size;
		// this->p_address = arr.p_address;    // 浅拷贝

		this->p_address = new T[m_capacity];   // 深拷贝

		// 将arr中的数据都拷贝过来
		for (int i = 0; i < this->m_size; i++)
		{
			this->p_address[i] = arr.p_address[i];
		}
	}

	// operator= 防止浅拷贝的问题
	myArray& operator= (const myArray& arr)
	{
		// 先置为空
		if (this->p_address != NULL)
		{
			delete[] this->p_address;
			this->p_address = NULL;
			this->m_capacity = 0;
			this->m_size = 0;
		}

		// 然后进行拷贝
		this->m_capacity = arr.m_capacity;
		this->m_size = arr.m_size;
		this->p_address = new T[m_capacity];   // 深拷贝

		// 将arr中的数据都拷贝过来
		for (int i = 0; i < this->m_size; i++)
		{
			this->p_address[i] = arr.p_address[i];
		}

		return *this;
	}

	// 尾插法
	void push_back(const T& val)
	{
		// 判断容量是否等于大小
		if (this->m_capacity == this->m_size)
			return;
		// 在数组尾部插入数据
		this->p_address[this->m_size] = val;
		this->m_size++;
	}

	// 尾删法
	void pop_back()
	{
		// 访问不到最后一个元素即可
		if (this->m_size == 0)
			return;
		this->m_size--;
	}

	// 通过下标访问数据
	T& operator[](int index)
	{
		return this->p_address[index];
	}

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

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


	// 析构函数
	~myArray()
	{
		if (this->p_address != NULL)
		{
			delete [] this->p_address;
			this->p_address = NULL;
			this->m_capacity = 0;
			this->m_size = 0;
		}
	}

private:

	T* p_address;
	int m_capacity;
	int m_size;

};

测试代码

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
using namespace std;
#include "数组类.hpp"

void printarr(myArray<int>& arr)
{
	for (int i = 0; i < arr.get_size(); i++)
	{
		cout << arr[i] << "\t";
	}
}

int main()
{
	myArray<int> arr1(5);
	for (int i = 0; i < 5; i++)
	{
		arr1.push_back(i);
	}
	printarr(arr1);
	cout << endl;
	cout << arr1.get_capacity() << endl;
	cout << arr1.get_size() << endl;

	myArray<int> arr2(5);
	arr2 = arr1;
	arr2.pop_back();
	cout << arr2.get_capacity() << endl;
	cout << arr2.get_size() << endl;

	return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值