cpp-实现数组模版类

    技术2026-01-03  13

    #include <iostream> #include <stdlib.h> using namespace std; template<class T> class MyArr{ public: MyArr(int capcity){ this->capcity = capcity; this->curLen = 0; this->arr = new T[this->capcity]; } MyArr(const MyArr<T> &arr){ int i = 0; this->capcity = arr.capcity; this->curLen = arr.curLen; this->arr = new T[arr.capcity]; for(;i<arr.curLen;i++){ this->arr[i] = arr.arr[i]; } } MyArr<T>& operator=(const MyArr<T>& arrCopy){ int i = 0; if(this->arr){ delete [] this->arr; } this->capcity = arrCopy.capcity; this->curLen = arrCopy.curLen; this->arr = new T[arrCopy.capcity]; for(;i<arrCopy.curLen;i++){ this->arr[i] = arrCopy.arr[i]; } return *this; } void pushBack(int data){ if(this->curLen>=this->capcity){ return; } this->arr[this->curLen] = data; this->curLen++; } T& operator[](int index){ //if(index>=this->curLen){ //return; //} return this->arr[index]; } ~MyArr(){ if(this->arr){ delete [] this->arr; } } public: int capcity; int curLen; T* arr; }; template<class T> ostream& operator<<(ostream& cout,MyArr<T>& arr){ int i = 0; while(i<arr.curLen){ cout << arr[i] << ","; i++; } return cout <<endl; }; int main(){ MyArr<int> arr(10); int a = 10,b=20; arr.pushBack(a); arr.pushBack(b); cout << arr; MyArr<int> arr2(10); arr2=arr; cout << arr; system("pause"); }
    Processed: 0.014, SQL: 9