十二周项目四 数组类运算的实现

/*copyright(c)2016.烟台大学计算机学院 
 * All rights reserved, 
 * 文件名称:text.Cpp 
 * 作者:舒文超 
 * 完成日期:2016年5月12日 
 * 版本号:vc++6.0 
 * 
 * 问题描述:设计数组类Array,为了实现测
            试函数中要求的功能,请补足
            相关的函数(构造、析构函数)
            和运算符重载的函数。 
  实现策略提示:可以将测试函数中的语句
                 加上注释,取消一句的注释,
                 增加相应的函数,以渐增地
                 实现所有的功能,避免全盘
                 考虑带来的困难。
 */
#include <iostream>
#include <iomanip>
#include <cassert>
using namespace std;

class Array
{
private:
    int* list;      //用于存放动态分配的数组内存首地址
    int size;       //数组大小(元素个数)
public:
    Array(int sz = 50);     //构造函数
    Array(int a[], int sz);     //构造函数
    Array(const Array &a);  //拷贝构造函数
    ~Array();          //析构函数
    Array operator + (const Array &a2);     //重载"="
    Array &operator = (const Array &a2);    //重载"="
    int &operator[] (int i); //重载"[]"
    const int &operator[] (int i) const;
    int getSize() const;        //取数组的大小
    void resize(int sz);        //修改数组的大小
    void show() const;
};

Array::Array(int sz)
{
    assert(sz >= 0);
    size = sz;
    list = new int [size];
}

Array::Array(int a[], int sz)
{
    assert(sz >= 0);
    size = sz;
    list = new int [size];
    for (int i = 0; i < size; i++) 
        list[i] = a[i];
}
Array::~Array()
{
    delete [] list;
}
Array::Array(const Array &a)
{
    size = a.size;
    list = new int[size];
    for (int i = 0; i < size; i++)
        list[i] = a.list[i];
}
Array Array::operator + (const Array &a2)
{
    assert(size == a2.size);
    Array total(size);
    for (int i = 0; i < size; i++)
        total.list[i] = list[i]+a2.list[i];
    return total
}
Array &Array::operator = (const Array& a2)
{
    if (&a2 != this)
    {
        if (size != a2.size)
        {
            delete [] list;
            size = a2.size;
            list = new int[size];
        }
        for (int i = 0; i < size; i++)
            list[i] = a2.list[i];
    }
    return *this;
}
int &Array::operator[] (int n)
{
    assert(n >= 0 && n < size);
    return list[n];
}
const int &Array::operator[] (int n) const
{
    assert(n >= 0 && n < size);
    return list[n];
}
int Array::getSize() const
{
    return size;
}
void Array::resize(int sz)
{
    assert(sz >= 0);
    if (sz == size)
        return;
    int* newList = new int [sz];
    int n = (sz < size) ? sz : size;
    for (int i = 0; i < n; i++)
        newList[i] = list[i];
    delete[] list;
    list = newList;
    size = sz;
}
void Array::show() const
{
    for (int i = 0; i < size; i++)
        cout<< list[i]<<" ";
    cout<<endl;
}
int main()
{
    int a[8]= {1,2,3,4,5,6,7,8};
    int b[8]= {10,20,30,40,50,60,70,80};
    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;
}

你可能感兴趣的:(十二周项目四 数组类运算的实现)