C++手写可扩展数组模板类

前言

仅做学习理解和参考!

// dome.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <functional>
using namespace std;
#include <vector>
const int ARRAY_SIZE = 3; //数组默认长度3
template<class T> //类模板,泛型。
class Array 
{
public:
	T* arr; //定义一个数组指针
	int t_size; //当前数组大小
	int p_size; //数组的总大小
public:
	Array(int p_size = ARRAY_SIZE):p_size(p_size), t_size(0) //初始化列表
	{
		this->arr = new T[p_size]; //申请p_size大小数组的内存。
	}
	~Array()
	{
		if (this->arr == 0) return; 
		delete[] this->arr; //释放内存
		this->arr = NULL;
	}

	void add(T num) 
	{
		if (this->t_size >= this->p_size) 
		{
			cout << "超出数组长度!" << endl;
			int temp_size = this->p_size + ARRAY_SIZE;
			T*temp_arr = new T[temp_size];// 创建新的长度数组指针
			for (size_t i = 0; i < this->p_size; i++){temp_arr[i] = this->arr[i];}//数据拷贝
			delete[] arr;// 释放原数组内存
			this->arr = temp_arr;
			this->p_size = temp_size;
		}
		this->arr[this->t_size] = num;
		this->t_size++;

	}
	void getArr()// 输出数组内容
	{
		for (size_t i = 0; i < this->t_size; i++)
		{
			cout << this->arr[i] << endl;
		}
	}
	
	operator T* ()// 重载函数返回数组
	{
		return this->arr;
	}

	T& operator [](int num)// 重载函数可a[1],返回内容
	{
		return this->arr[num];
	}

	void operator +(T num) // 重载函数,功能与add()方法一致,可a+1表达式实现add方法
	{
		if (this->t_size >= this->p_size)
		{
			cout << "超出数组长度!" << endl;
			int temp_size = this->p_size + ARRAY_SIZE;
			T* temp_arr = new T[temp_size];// 创建新的长度数组指针
			for (size_t i = 0; i < this->p_size; i++) { temp_arr[i] = this->arr[i]; }//数据拷贝
			delete[] arr;// 释放原数组内存
			this->arr = temp_arr;
			this->p_size = temp_size;
		}
		this->arr[this->t_size] = num;
		this->t_size++;
	}
	
};
int main()
{

	Array<string> a;
	a.add("223"); a + "haha"; a + "333"; a + "333";
	a.getArr();
	cout << "-------------" << endl;
	a[1] = "888";
	cout << a[1] << endl;
	return 0;
}

结果

猜你喜欢

转载自blog.csdn.net/weixin_47723549/article/details/134071504