已解决
C++手写可扩展数组模板类
来自网友在路上 178878提问 提问时间:2023-10-27 20:56:45阅读次数: 78
最佳答案 问答题库788位专家为你答疑解惑
前言
仅做学习理解和参考!
// 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;
}
结果
查看全文
99%的人还看了
相似问题
猜你感兴趣
版权申明
本文"C++手写可扩展数组模板类":http://eshow365.cn/6-26315-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!