MyArray數組筆記(模板的使用 )

MyArray數組筆記

#define _CRT_NO_SECURE_WARNINGS
#include<iostream>
using namespace std;
template<class T>
class MyArray
{
public:
    MyArray(int capacity)
    {
        this->mcapacity = capacity;
        this->msize = 0;
        this->mpaddr = new T[this->mcapacity];


    }
    MyArray (const MyArray<T> &arr)
    {
        this->msize = arr.msize;
        this->mcapacity = arr.mcapacity;
        this->mpaddr = new T[this->mcapacity];
        for ( i = 0; i < this->msize; i++)
            {
            this->mpaddr[i] = arr.mpaddr[i];

            }
    }
    MyArray operator=(const MyArray<T> &arr)//重載拷貝構造
    {

        if (this->mpaddr!=NULL)
        {
            delete[] this->mpaddr;
        }
        this->msize = arr.msize;
        this->mcapacity = arr.mcapacity;
        this->mpaddr = new T[this->mcapacity];
        for (i = 0; i < this->msize; i++)
        {
            this->mpaddr[i] = arr.mpaddr[i];

        }
        return *this
    }
    T & operator[](int index)//重載[]
    {

        this->mpaddr[index];

    }
    //容器都是值寓意,而非引用寓意,向容器中放入元素,都是放入拷貝分
    void PushBack(T &&data)//雙引用可以接受右值
    {
        if (this->msize!=this->mcapacity)
        {
            this->mpaddr[msize] = data;
        }
        this->msize++;

    }

    ~MyArray()
    {
        if (this->mpaddr!=NULL)
        {
            delete[] this->mpaddr;
        }
    }


public:
    //一共可以容下多少個元素
    int msize;
    //當前數組有多少元素
    int mcapacity;
    //保存數據的首地址
    int *mpaddr;
private:

};
void test()
{
    MyArray<int>p(10);
    p.PushBack(10);
    p.PushBack(20);
    for ( int i = 0; i < p.msize; i++)
    {
        cout << p.mpaddr[i] << endl;
    }

}

int main(void)
{
    test();
    system("pause");


}

結果

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章