• 动态数组类的设计


    程序代码如下,主要结合了运算符重载的特点进行数组类的设计。实现了数组的插入,复制等功能,通过这个程序对vector容器有了一定的了解。

    #include <iostream>
    
    using namespace std;
    
    class Array
    {
    private :
        int size;
        int *ptr;
    public :
        Array(int s = 0);
        Array(const Array &a);
        ~Array();
        void push_back(int v);
        Array & operator =(const Array &a);
        int length()
        {
            return size;
        }
        int & Array::operator[](int i)
        {
            return ptr[i];
        }
    };
    Array::Array(int s )
    {
        if (s == 0)
            ptr = NULL;
        else
        {
            ptr = new int[s];
        }
        size = s;
    }
    Array::Array(const Array &a)
    {
        if (!a.ptr)
        {
            ptr = NULL;
            size = 0;
            return;
        }
        ptr = new int[a.size];
        memcpy(ptr, a.ptr, sizeof(int)*a.size);
        size = a.size;
    }
    Array & Array::operator =(const Array &a)
    {
        if (ptr == a.ptr)
            return (*this);
        if (a.ptr == NULL)
        {
            if (ptr)
                delete[] ptr;
            ptr = NULL;
            size = 0;
            return (*this);
        }
        if (size < a.size)
        {
            delete[] ptr;
            ptr = new int[a.size];
            memcmp(ptr, a.ptr, a.size * sizeof(int));
        }
        else
        {
            memcmp(ptr, a.ptr, a.size * sizeof(int));
        }
        size = a.size;
        return (*this);
    }
    Array::~Array()
    {
        if (ptr)
            delete[] ptr;
    }                                   
    void Array::push_back(int v)
    {
        if (ptr)
        {
            int *tmp = NULL;
            tmp = new int[size + 1];
            memcpy(tmp, ptr, sizeof(int)*size);
            delete[] ptr;
            ptr = tmp;
        }
        else
            ptr = new int[1];
        ptr[size++] = v;
    }
    int main()
    {
        Array a;
        for (int i = 1; i < 3; i++)
            a.push_back(i);
        for (int i = 0; i < a.length(); i++)
            cout << a[i] << endl;
        return 0;
    }

  • 相关阅读:
    [C++] split string by string
    工作三个月心得经验
    Ubuntu Command-Line: Enable Unlimited Scrolling in the Terminal
    What is the PPA and How to do with it ?
    WCF vs ASMX WebService
    The ShortCuts in the ADT (to be continued)
    when does the View.ondraw method get called
    Browsing Storage Resources with Server Explorer
    Get start with Android development
    C++ Frequently asking question
  • 原文地址:https://www.cnblogs.com/helloforworld/p/5655242.html
Copyright © 2020-2023  润新知