zoukankan      html  css  js  c++  java
  • C++自定义数组

    #ifndef _MYARRAY_H_
    #define _MYARRAY_H_
    #include<iostream>
    #include<string>

    template<class T>
    class Myarray {

    public:
    //默认构造
    Myarray(int capcity);
    //拷贝构造
    Myarray(const Myarray<T>& arr);
    //重载[]
    T& operator[](int index);
    //重载=
    Myarray<T>& operator=(const Myarray<T>& arr);
    //在数组后面追加元素
    void Pushback(T& data);
    //对右值去引用
    void Pushback(T&& data);
    ~Myarray();


    public:
    int m_Capacity;//总共能存多大的数据
    int m_Size;//现在的数据尺寸
    T* p_Addr;//数据指针
    private:

    };

    template<class T>
    Myarray<T>::Myarray<T>(int capcity) {
    this->m_Capacity = capcity;
    this->m_Size = 0;
    this->p_Addr = new T[this->m_Capacity];


    }
    //拷贝构造
    template<class T>
    Myarray<T>::Myarray<T>(const Myarray<T>& arr) {
    this->m_Size = arr.m_Size;
    this->m_Capacity = arr.m_Capacity;
    this->p_Addr = new T[this->m_Capacity];
    for (int i = 0; i < this->m_Size; i++) {
    this->p_Addr[i] = arr.p_Addr[i];
    }
    }

    template<class T>
    T& Myarray<T>::operator[](int index) {
    return this->p_Addr[index];

    }

    template<class T>
    Myarray<T>& Myarray<T>::operator=(const Myarray<T>& arr) {
    if (this->p_Addr != NULL) {
    delete[] this->p_Addr;
    }
    this->m_Size = arr.m_Size;
    this->m_Capacity = arr.m_Capacity;
    this->p_Addr = new T[this->m_Capacity];
    for (int i = 0; i < this->m_Size; i++) {
    this->p_Addr[i] = arr.p_Addr[i];
    }

    return *this;
    }

    template<class T>
    void Myarray<T>::Pushback(T& data) {

    //先判断容器中是否有位置
    if (this->m_Size >= this->m_Capacity) {
    return;
    }
    this->p_Addr[this->m_Size] = data;
    this->m_Size++;
    }

    template<class T>
    void Myarray<T>::Pushback(T&& data) {

    //先判断容器中是否有位置
    if (this->m_Size >= this->m_Capacity) {
    return;
    }
    this->p_Addr[this->m_Size] = data;
    this->m_Size++;
    }

    template<class T>
    Myarray<T>::~Myarray() {
    if (this->p_Addr != NULL) {
    delete[] this->p_Addr;

    }

    }


    #endif // !_MYARRAY_H_

  • 相关阅读:
    使用过滤器(Filter)解决请求参数中文乱码问题(复杂方式)
    JDBC-自定义数据库工具类(DBService)
    Dbutils学习(介绍和入门)
    JAVA中简单的MD5加密类(MD5Utils)
    TCP/IP网络编程系列之三(初级)
    Linux C编程学习
    sharepoint 2010 创建自定义的ASP.NET Web Service (上)
    TCP/IP网络编程系列之四(初级)
    TCP/IP网络编程系列之二(初级)
    TCP/IP网络编程系列之一(初级)
  • 原文地址:https://www.cnblogs.com/shuimuqingyang/p/13962070.html
Copyright © 2011-2022 走看看