c++ - 具有通用大小 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];
}
}
解决方案
在这种情况下,您可以应用零规则:
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
}
推荐阅读
- typescript - 带有条件属性的接口
- php - reCAPTCHA v3 验证分数出现问题
- ios - 从 EKEventStore 获取事件的问题
- for-loop - 当循环完成时,FOR 循环中的比较值不会与正确的向量元素相关联。- 代码审查
- reactjs - redux 的 state 对象中的这些附加属性是什么?
- c# - 无法从文件加载 X.509 证书
- reactjs - 为什么即使 mapStateToProps 返回相同的 (===) 道具,我的连接组件也会重新渲染?
- r - 时间序列ggplot中x轴上的时间戳
- visual-studio - XSLT 1.0 修改配置文件替换功能
- c# - 泛型方法上的 C# 协方差