C++编程:定义一个动态数组类模板

包括表示数组元素个数和数组元素首地址的两个数据成员,一个带参数的构造函数和一个无参的构造函数(默认元素个数为10),一个用于输出数组元素的成员函数,同时要求重载<<运算符,实现使用cout对象输出动态数组。

#include <bits/stdc++.h>
using namespace std;

template <class T> 
class myarray{
public:
    int len;
    T* t;
    myarray(){
        len = 10;
        t = new T[len];
        if (!this->t)
        {
            cout << "fail" << endl;
            exit(1);
        }
    }

    myarray(int l, T* other){
        this->len = l;
        t = new T[l];
        if (!this->t)
        {
            cout << "fail" << endl;
            exit(1);
        }
        strcpy(t,other);
    }

    T* getArray(){
        return this->t;
    }



    T& operator[](int i){
        if (i < 0 || i > this->len - 1)
        {
            cout << "fail" << endl;
            exit(2);
        }
        return (this->t)[i];
    }   

    friend ostream& operator <<(ostream& os, const myarray& ob){
        for(int i = 0;i<ob.len;i++){
            os<<(ob.t)[i]; 
        }
        return os;
    }
    ~myarray(){
        delete[] t;
        t = nullptr;
    }
};
int main(){
    myarray<string> a;
    a[0] = "00";
    a[1] = "01";
    a[2] = "02";
    a[3] = "03";
    a[4] = "04";
    a[5] = "05";
    a[6] = "06";
    a[7] = "07";
    a[8] = "08";
    a[9] = "09";

    cout<<a<<endl;
    return 0;
}