第十四周上机实践——项目3-数组类模板

/*
 *Copyright (c)2016,烟台大学计算机与控制工程学院
 *All rights reserved.
 *文件名称:main.cpp
 *作    者:郭永恒
 *完成日期:2016年6月1日
 *版 本 号:v1.0
 *
 *问题描述:把十二周项目3的数组类改为模板类
 */

#include 
using namespace std;

template 
class Array
{
public:
    //构造函数
    Array():list(nullptr),size(0){};
    Array(T *ar,unsigned int len):size(len)
    {
        list = new T[size];
        for(unsigned int i = 0; i < len; ++i)
            list[i] = ar[i];
    }
    Array(const Array&);
    //下标运算符
    T& operator[](unsigned int n)
    { return list[n];}
    const T& operator[](unsigned int n) const
    { return list[n];}
    //赋值运算符
    Array& operator=(const Array& arr);
    //合并数组
    Array operator+(const Array& arr);
    void resize(unsigned int n);
    void show();
    ~Array(){delete [] list;}
private:
    T *list;
    unsigned int size;
};

template 
Array::Array(const Array& arr)
{
    if(list != nullptr)
        delete [] list;
    size = arr.size;
    list = new T[size];
    for(unsigned int i = 0; i < size; ++i)
        list[i] = arr[i];
}

template 
Array Array::operator+(const Array& arr)
{
    unsigned int i;
    unsigned int len = this->size+arr.size;
    T *t = new T[len];
    for(i = 0; i < this->size; ++i)
        t[i] = (*this)[i];
    for(unsigned int j = 0; j < arr.size; ++i,++j)
        t[i] = arr[j];
    Array temp(t,len);
    delete [] t;
    return temp;
}

template 
Array& Array::operator=(const Array& arr)
{
    if(this != &arr)
    {
        if(list != nullptr)
            delete [] list;
        size = arr.size;
        list = new T[size];
        for(unsigned int i = 0; i < size; ++i)
            list[i] = arr[i];
        return *this;
    }
    return *this;
}

template 
void Array::resize(unsigned n)
{
    if(list == nullptr)
    {
        list = new T[n];
        size = n;
        return ;
    }
    else
    {
        T *temp = new T[n];
        for(unsigned i = 0; i < size; ++i)
            temp[i] = list[i];
        delete [] list;
        list = temp;
        size = n;
        return ;
    }
}

template 
void Array::show()
{
    for(unsigned i = 0; i < size; ++i)
        cout << list[i] << " ";
    cout << endl;
    return ;
}

int main()
{
    double a[8] = {1.1,2.1,3.1,4.1,5.1,6.1,7.1,8.1};
    double b[8] = {10.1,20.1,30.1,40.1,50.1,60.1,70.1,80.1};
    Array array1(a,8),array3,array4;
    const Array array2(b,8);
    array4 = array3 = array1 + array2;
    array3.show();
    array4.resize(20);
    array4[8] = 99;
    cout << array4[8] << endl;
    cout << array2[3] << endl;
    return 0;
}

运行结果:

第十四周上机实践——项目3-数组类模板_第1张图片

你可能感兴趣的:(作业)