数组模板类

#include 
/*.设计一个数组模板类,完成对int ,char及自定义类型元素的管理
  需要实现:构造函数,拷贝构造函数,<< ,[],  = 操作符重载
*/
using namespace std;
template <typename T>
class myArrary
{
   public:

    friend ostream & operator<<(ostream &os,const myArrary<T> &other)
    {
        for(int i =0;i<other.size;i++)
        {
            os << other.array[i] <<" ";
        }
        return os;
    }
    myArrary(int size = 0);
    ~myArrary();
    int getLen();
    myArrary(const myArrary &other);//拷贝构造函数
    //数组元素类型操作符重载[]
    T& operator[](const int index);
    //整个对象操作符重载 =
    myArrary &operator=(const myArrary &other );
private:
    int size;
    T *array;
};

int main()
{
    myArrary<int> A(20);
    for(int i= 0;i<A.getLen();i++)
      {
        A[i] = i;
      }
    for(int i =0;i<A.getLen();i++)
    cout << A[i] <<endl;

    cout << A <<endl;
    return 0;
}


template<class T>
myArrary<T>::myArrary(int size):size(size)
{
    array = new T[size];
}
template<class T>
myArrary<T>::~myArrary()
{
    cout << "~myArrary()" <<endl;
}
template<class T>
int myArrary<T>::getLen()
{
    return this->size;
}
template<class T>
myArrary<T>::myArrary(const myArrary<T> &other)
{
    this->size = other.size;
    this->array = new T[size];
    for(int i = 0;i<size;i++)

    {
        this->array[i] = other.array[i];
    }
}

template<class T>
T &myArrary<T>::operator[](int index)
{
    return array[index];
}

template<class T>
myArrary<T> &myArrary<T>::operator=(const myArrary &other)
{
    if(this->array != nullptr)
    {
        delete []array;
        array = nullptr;
        this->size = 0;
    }
    this->size = other.size;
    this->array = new T[size];

    for(int i = 0;i< size;i++)
    {
        this->array[i] = other.array[i];
    }
    return *this;
}


需要注意的是 模板类的 << 运算符重载不能在类外实现```,不然相当于重新定义了一个模板,因为<< 函数不属于类

再加个我搜索到的博主的解释
https://blog.csdn.net/newmerce/article/details/6819022?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.nonecase&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.nonecase

你可能感兴趣的:(c++)