当前位置: 首页 > article >正文

C++ 使用c++类模板实现动态数组-可实现自定义数据类型存储

.hpp文件

#include <iostream>
#include <cstdlib>
#include <cstring>
using namespace std;
template <class T>
class arraylist
{
private:
    T* data ;//数组地址
    int size;//长度
    int count;//容量

public:
    arraylist();
    ~arraylist();
    void add(T t);
    T& get(int index);
    int getsize();
};
template <class T>
arraylist <T>:: arraylist()
{
    this->count = 2;
    this->size = 0;
    this->data = new T[count];
}
template <class T>
arraylist<T>::~arraylist()
{
    if(data != NULL)
    {
        delete [] data;
        data = NULL;
    }
}
template <class T>
void arraylist<T>::add(T t)
{
    if(size == count)
    {
        count  = count * 2;
        T* newdata = new T[count];
        memcpy(newdata,data,size*sizeof(T));
        delete [] data;
        data = newdata;
    }
    data[size] = t; 
    size++;
}
template <class T>
T& arraylist<T>::get(int index)
{
    return data[index];
}

template <class T>
arraylist<T>::getsize()
{
   return size;
}

.main文件

#include <iostream>
#include <cstring>
#include <cstdlib>
#include "arraylist.hpp"
using namespace std;
class person
{
private:
    char name[50];
    int age;
public:
    person(){}
    person(char *name,int age)
    {

        strcpy(this->name,name);
        this->age = age;
    }
    char *getname()
    {
        return name;
    }
    void setname(char *name)
    {
        strcpy(this->name,name);
    }
    void showinformation()
    {
        cout << "姓名" << name << "\n年龄" << age <<endl;
    }
};
void fun01()
{
    person p1("张三",18);
    person p2("张四",18);
    person p3("张寺",18);
    person p4("张死",18);
    person p5("张斯",18);
    arraylist<person>ps;
    ps.add(p1);
    ps.add(p2);
    ps.add(p3);
    ps.add(p4);
    ps.add(p5);
    int len = ps.getsize();
    cout << "len=" << len << endl;
    for(int i = 0 ;i < len;i++)
    {
        ps.get(i).showinformation();
    }
}

int main(int argc, char *argv[])
{
    fun01();
    return 0;
}

运行结果:


http://www.kler.cn/a/137530.html

相关文章:

  • 软件临界资源访问冲突
  • python运算符重载之构造函数和迭代器
  • 家庭教育专家:如何创建家庭自主学习环境?
  • 【MySQL--->用户管理】
  • 移远通信推出六款新型天线,为物联网客户带来更丰富的产品选择
  • IDEA-运行测试方法提示Command line is too long
  • vivado产生报告阅读分析13-时序报告9
  • YOLOv8更换骨干网络HorNet:递归门控卷积的高效高阶空间交互——涨点神器!
  • C++基础从0到1入门编程(三)
  • STM32获取最大堆栈空间
  • 生成式 AI 落地制造业的关键是什么?亚马逊云科技给出答案
  • MindSpore基础教程:使用 MindCV和 Gradio 创建一个图像分类应用
  • shell脚本之条件语句
  • 鸿蒙系统扫盲(二):再谈鸿蒙是不是安卓套壳?
  • 全志XR806基于http的无线ota功能实验
  • 开发知识点-uniapp微信小程序-开发指南
  • 阿里云3M固定带宽服务器速度快吗?是否够用?
  • 本地私域线上线下 线上和线下的小程序
  • spring面试题合集介绍
  • vivado产生报告阅读分析14-时序报告10