zoukankan      html  css  js  c++  java
  • 数据结构练习(14)含有指针成员的类的拷贝

    http://zhedahht.blog.163.com/blog/static/25411174200722710364233/

    上次面试就被问到copy constructor,无奈C++白痴了,这两天狂啃C++ primer和JAVA的时候感觉很多问题似曾相识。

    C++果然很强大,用起来神清气爽,是时候入门C++了!

    另外看到了stackoverflow上面一个关于unsigned的讨论:

    http://stackoverflow.com/questions/2099830/unsigned-keyword-in-c

    #include <iostream>
    using namespace std;
    
    template <typename T> class Array
    {
    public:
        Array(unsigned arraysize) : data(0), size(arraysize)
        {
            if (size > 0)
                data = new T[size];
        }
        Array(const Array& copy) : data(0), size(copy.size)
        {
            if (size > 0)
            {
                data = new T[size];
                for (unsigned i = 0; i < size; ++i)
                    setvalue(i, copy.getvalue(i));
            }
        }
        const Array& operator = (const Array& copy)
        {
            if (this == &copy)
                return *this;
    
            if (data != NULL)
            {
                delete []data;
                data = NULL;
            }
    
            size = copy.size;
            if (size > 0)
            {
                data = new T[size];
                for (unsigned i = 0; i < size; ++i)
                    setvalue(i, copy.getvalue(i));
            }
        }
        ~Array()
        {
            if (data)
                delete []data;
        }
        void setvalue(unsigned index, const T& value)
        {
            if (index < size)
                data[index] = value;
        }
        T getvalue(unsigned index) const
        {
            if (index < size)
                return data[index];
            else
                return T();
        }
    
    private:
        T* data;
        unsigned size;
    };
    
    int main()
    {
        Array<int> a(10);
        Array<int> b(10);
        b = a;
        return 0;
    }
    -------------------------------------------------------

    kedebug

    Department of Computer Science and Engineering,

    Shanghai Jiao Tong University

    E-mail: kedebug0@gmail.com

    GitHub: http://github.com/kedebug

    -------------------------------------------------------

  • 相关阅读:
    hdu 4508
    hdu 4506
    hdu 4505
    hdu 1525
    hdu 2212
    (贪心)删数问题
    (最短路 Dijkstra) hdu 1544
    (次小生成树) poj 1679
    (prim)hdu 1102
    (kruskal)hdu 1863
  • 原文地址:https://www.cnblogs.com/kedebug/p/2814970.html
Copyright © 2011-2022 走看看