首页 > 解决方案 > 具有通用大小 C++ 的通用数组

问题描述

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

先感谢您。

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];
    }
}

标签: c++

解决方案


在这种情况下,您可以应用零规则

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;

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

template <class T,int SIZE>
Array<T,SIZE>::Array(const Array& a)
: s(a.s) // note the member initializer
{
    // empty body
}

推荐阅读