类模板案例——通用数组

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

可以对内置数据类型以及自定义数据类型进行存储

将数组中的数据存储到堆区

提供对应的拷贝构造函数以及operator=防止浅拷贝问题

提供尾插法和尾删法对数组中的数据进行增加和删除

可以通过下标的方式访问数组中的元素

可以获取数组的容量和当前元素的个数

类模板代码:Array.hpp

#pragma once
#include <iostream>
using namespace std;

template<class T>
class MyArray{
public:
    MyArray(int capacity){
        this->m_capacity=capacity;
        this->m_size=0;
        this->pAddress=new T[this->m_capacity];
    }
    ~MyArray(){
        if(this->pAddress!=NULL) {
            delete[] this->pAddress;
            this->pAddress=NULL;
        }
    }
    //尾插入
    void Push_Back(const T &val) {
        if(this->m_capacity==this->m_size) return;
        this->pAddress[this->m_size++]=val;
    }
    //尾删除
    void Pop_Back(){
        if(this->m_size==0) return;
        this->m_size--;
    }
    //下标访问数组
    T& operator [] (int index) {
      return this->pAddress[index];
    }
    //返回数组容量
    int getCapacity() {
        return this->m_capacity;
    }
    //返回数组大小
    int getSize() {
        return this->m_size;
    }
    MyArray(const MyArray& arr){
        this->m_capacity=arr.m_capacity;
        this->m_size=arr.m_size;
        this->pAddress=new T[this->m_capacity];
        for(int i=0;i<this->m_size;++i) {
            this->pAddress[i]=arr.pAddress[i];
        }
    }
    MyArray& operator = (const MyArray& arr){
        this->m_capacity=arr.m_capacity;
        this->m_size=arr.m_size;
        if(this->pAddress!=NULL) {
            delete[] this->pAddress;
            this->pAddress=NULL;
        }
        this->pAddress=new T[this->m_capacity];
        for(int i=0;i<this->m_size;++i) {
            this->pAddress[i]=arr.pAddress[i];
        }
        return *this;
    }
public:
    T *pAddress;
    int m_size;
    int m_capacity;
};

测试代码 main.cpp

#include <iostream>
#include "Array.hpp"

using namespace std;
template<class NameType,class AgeType>
class Person{
public:
    Person(){

    }
    Person(NameType name,AgeType age){
        this->age=age;
        this->name=name;
    }
    void show() {
        cout<<age<<" "<<name<<endl;
    }
    NameType name;
    AgeType age;
};
void test() {
    MyArray<Person<string,int> >P(4);
    P.Push_Back(Person<string,int>{"小明",22});
    P.Push_Back(Person<string,int>{"李华",18});
    P[0].show();
    P[1].show();
    cout<<P.getSize()<<endl;
    cout<<P.getCapacity()<<endl;
}
int main()
{
    test();
    MyArray<int> a(100);
    cout<<a.getCapacity()<<endl;
    for(int i=0;i<50;i++) {
        a.Push_Back(i);
    }
    cout<<a.getSize()<<endl;
    cout<<a[45]<<endl;
    a[1]=a[44]=99;
    cout<<a[1]<<endl;
    a.Pop_Back();
    cout<<a.getSize()<<endl;
    return 0;
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值