代码之家  ›  专栏  ›  技术社区  ›  Sam12

具有通用尺寸C++的通用数组

c++
  •  3
  • Sam12  · 技术社区  · 7 年前

    这是我的泛型类数组,我想问一下复制构造函数和赋值,这是正确的方法吗?如果是,那么我真的需要在类中插入它们吗?

    template <class T, int SIZE>
    class Array {
        T data[SIZE];
    
    public:
        explicit Array();
        Array(const Array& a); //copy constructor
        ~Array(); //destructor
        Array& operator=(const Array& a); //assignment
        T& operator[](int index);
        const T& operator[](int index) const;
    };
    
    
    template <class T,int SIZE>
    Array<T,SIZE>::Array()
    {
    }
    
    template <class T,int SIZE>
    Array<T,SIZE>::~Array()
    {
    
    }
    
    template <class T,int SIZE>
    Array<T,SIZE>::Array& operator=(const Array& a)
    {
        for(int i=0;i<SIZE;i++)
        {
            data[i]=a[i];
        }
        return *this;
    }
    
    template <class T,int SIZE>
    Array<T,SIZE>::Array(const Array& a)
    {
        for(int i=0;i<SIZE;i++)
        {
            data[i]=a[i];
        }
    }
    
    2 回复  |  直到 7 年前
        1
  •  4
  •   Acorn    7 年前

    在这种情况下,可以应用 Rule of Zero :

    template <class T, int SIZE>
    class Array {
        T data[SIZE];
    
    public:
        T& operator[](int index);
        const T& operator[](int index) const;
    };
    

    在这种情况下,需要将赋值运算符的签名固定到(即,您发布的代码无法编译):

    template <class T,int SIZE>
    Array<T,SIZE>& Array<T,SIZE>::operator=(const Array& a)
    

    data operator[] (除非你有理由):

    data[i] = a.data[i]; // note `a.data[i]` vs. `a[i]`
    

    struct

    template <class T, int SIZE>
    class Array {
        struct S {
            T data[SIZE];
        } s;
    
        // ...
    };
    

    以便您可以将循环替换为:

    s = a.s;
    

    不仅如此,而且使用 结构 将允许您复制构造数组的元素,而不是复制分配它们(就像您在循环中所做的那样),这对某些人来说可能很重要 T 类型:

    template <class T,int SIZE>
    Array<T,SIZE>::Array(const Array& a)
    : s(a.s) // note the member initializer
    {
        // empty body
    }
    
        2
  •  0
  •   Richard Hodges    7 年前

    这将解决编译器错误:

    template <class T,int SIZE>
    auto Array<T,SIZE>::operator=(const Array& a) -> Array&
    {
        for(int i=0;i<SIZE;i++)
        {
            data[i]=a[i];
        }
        return *this;
    }