C++小实践--自定义数组

要求

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

  • 可以对内置数据类型以及自定义数据类型的数据进行存储
  • 将数组中的数据存储到堆区
  • 构造函数中可以传入数组的容量
  • 提供对应的拷贝构造函数以及operator=防止浅拷贝问题
  • 提供尾插法和尾删法对数组中的数据进行增加和删除
  • 可以通过下标的方式访问数中的元素
  • 可以获取数组中当前元素个数和数组的容量

myArray.hpp

#pragma once //防止文件被重复包含
#include "iostream"


using namespace std;

template <class T>
class myArray{
private:
    T *t;
    int capacity;
    int size;
public:
    myArray(){
        capacity = 5;
        size = 0;
        t=new T[capacity];
    }
    //有参构造函数
    myArray(int cap):t(new T[cap]),capacity(cap),size(0){
        //cout<<"有参构造"<<endl;
    }
    myArray(const myArray&a){
        //cout<<"拷贝构造"<<endl;
        this->size = a.size;
        this->capacity = a.capacity;
        this->t = new T[a.capacity];
        for (int i = 0; i < a.size; ++i) {
            this->t[i] = a.t[i];
        }
    }

    myArray& operator=(const myArray &a){
        //原先堆中有数据那么先清空  要返回引用 因为就是自己本身 this
        if (this->t!= nullptr){
            delete[]t;
            t= nullptr;
            capacity=0;
            size=0;
        }
        //cout<<"等号重载"<<endl;
        capacity=a.capacity;
        size=a.size;
        t=new T[capacity];
        for (int i = 0; i < size; ++i) {
            t[i] = a.t[i];
        }
        return *this;
    }
    ~myArray(){
        if (t!= nullptr){
            delete[]t;
            t = nullptr;
        }
    //cout<<"析构函数"<<endl;
    }

    //尾插法
    bool pushBack(const T&t){
        if (capacity==size)
            return false;
        this->t[size] = t;
        size++;
        return true;
    }

    //尾删法
    bool popBack(){
        if (size==0)
            return false;
        this->size--;
        return true;
    }

    //通过下标方式访问数组元素
    //函数调用的结果要作为左值存在,返回引用
    T& operator[](int index){
        if (index>size||index<0)
            throw "下标越界";
        return this->t[index];
    }

    //返回容量
    int getCapacity(){
        return capacity;
    }

    //返回大小
    int getSize(){
        return size;
    }
};
  • 7
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值