gpt4 book ai didi

c++ - 具有通用大小的通用数组 C++

转载 作者:太空狗 更新时间:2023-10-29 20:51:17 24 4
gpt4 key购买 nike

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

提前谢谢你。

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

最佳答案

在这种情况下,您可以应用 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;

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

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

关于c++ - 具有通用大小的通用数组 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50898773/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com