数组类运算的实现

来源:互联网 发布:云南进出口贸易数据 编辑:程序博客网 时间:2024/06/06 10:59
#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;
}
0 0
原创粉丝点击