類模板——MyArray框架搭建和函數實現

#include<iostream>
using namespace std;

template<class T>
class MyArray{
public:
    MyArray(int capacity){
        this->mCapacity = capacity;
        this->mSize = 0;
        //申請內存
        this->pAddr = new T[this->mCapacity];//初試一個capacity大的空間
    }
    ~MyArray(){
        if (this->pAddr != NULL){
            delete[]pAddr;
        }
    }
    MyArray(const MyArray& arr)//拷貝構造函數,使用const,防止傳入參數改變
    {
        this->mSize = arr.mSize;
        this->mCapacity = arr.mCapacity;
        //申請內存空間
        this->pAddr = new T[this->mCapacity];
        //數據拷貝
        for (int i = 0; i < this.mSize; i++){
            this->pAddr[i] = arr.pAddr[i];
        }
    }

    T& operator[](int index){
        return this->pAddr[index];
    }

    MyArray<T> operator=(const MyArray<T>& arr){
        //如果有,釋放空間
        if (this->pAddr!=NULL){
            delete[] this->pAddr;
        }
        this->mSize = arr.mSize;
        this->mCapacity = arr.mCapacity;
        //申請內存空間
        this->pAddr = new T[this->mCapacity];
        //數據拷貝
        for (int i = 0; i < this.mSize; i++){
            this->pAddr[i] = arr.pAddr[i];
        }
        return *this;
    }

    void PushBack(T& data){
        //判斷容器中是否有位置
        if (this->mSize >= this->mCapacity){
            return;
        }
        //調用拷貝構造後者 =號操作符重載
        //1.對象元素必須能夠被拷貝
        //2.容器都是值寓意,而非引用寓意,向容器中放入元素,都是放入的元素的拷貝份,而非本身
        //3.如果元素的成員有指針,注意深拷貝和淺拷貝的問題;
        this->pAddr[this->mSize] = data;
        this->mSize++;
    }
    //T&&對右值進行取引用,c++11的新標準
    void PushBack(T&& data){
        //判斷容器中是否有位置
        if (this->mSize >= this->mCapacity){
            return;
        }
        this->pAddr[this->mSize] = data;
        this->mSize++;
    }

public:
    //一共可以容下多少個元素
    int mCapacity;
    //當前數組有多少元素
    int mSize;
    //保存數據的首地址
    T* pAddr;
};



void test01(){
    MyArray<int>marray(20);
    int a = 10, b = 20, c = 30, d = 40;
    marray.PushBack(a);
    marray.PushBack(b);
    marray.PushBack(c);
    marray.PushBack(d);

    //不能對右值取引用
    //左值 可以在多行使用
    //右值 臨時變量 只能在當前行使用
    marray.PushBack(100);
    marray.PushBack(200);
    marray.PushBack(300);

    for (int i = 0; i < marray.mSize; i++){
        cout << marray[i] << " ";
    }
    cout << endl;
}

class Person{};

void test02(){
    Person p1, p2;
    MyArray<Person>arr(10);
    arr.PushBack(p1);
    arr.PushBack(p2);

}
int main()
{
    cout<<"hello world"<<endl;
    test01();
    test02();
    return 0;
}

總結:
1、瞭解左值、右值的概念;
2、複習淺拷貝和深拷貝的區別;

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