模板类,并将数组初始化为零

Template classes and initializing an array to zero

本文关键字:数组 初始化      更新时间:2023-10-16

我今天早些时候发布了关于模板类的文章,但离我之前的问题还有很长的路要走,并从这里得到了解决方案。当然,当这个问题得到解决时,总有一个新的问题我似乎想不出来。

给定以下构造函数:

template <typename Type, int inSize>
sortedVector<Type, inSize>::sortedVector():
    size(inSize), vector(new Type[inSize]), amountElements(0)
{}

我想制作一个动态数组,然后可以通过add方法将任何类型的元素插入其中。来自main的呼叫如下所示:

sortedVector<Polygon, 10> polygons;
sortedVector<int, 6> ints;

构造数组时,如何将其初始化为零?我不能将对象设置为零;)

我觉得我很聪明,试着重载Polygon的=运算符,如果给它一个int,它什么都不会做。事实证明我做不到):

有什么好的建议吗?

此外,这里还有模板类sortedVector:

template <typename Type, int inSize>
class sortedVector
{
public:
    sortedVector();
    int getSize();
    int getAmountElements()
    bool add(const Type &element);
private:
    Type *vector;
    int size;
    int amountElements;
};

还有Polygon:

class Polygon
{
public:
    Polygon();
    Polygon(Vertex inVertArr[], int inAmountVertices);
    ~Polygon();
    void add(Vertex newVer);
    double area();
    int minx();
    int maxx();
    int miny();
    int maxy();
    int getAmountVertices() const;        
    friend bool operator > (const Polygon &operand1, const Polygon &operand2);
    friend bool operator < (const Polygon &operand1, const Polygon &operand2);
private:
    Vertex *Poly;
    int amountVertices;
};

将数组元素初始化为Type()。这就是标准库容器的作用。对于内置的数字类型,Type()相当于0。对于类/结构类型,Type()构造一个临时默认构造的对象。

您只需使用Type()即可获得默认构造的对象。一种更好的方法是直接使用std::vector<T>,或者通过添加所需的任何功能或约束的瘦包装器来使用。尽管没有std::vector<T>是可行的,但任何真正正确管理资源和对象的解决方案最终都会重新实现std::vector<T>的至少一部分。

只需将"vector"(顺便说一句,鉴于std::vector<>的突出性,名称令人困惑)的每个元素指定为默认值。默认值仅为Type(),因此您可以在构造函数主体中执行以下操作:

std::fill(vector, vector + size, Type());

构造数组时,如何将其初始化为零?我可以未将对象设置为零;)

您可以使用所谓的默认构造值。换句话说,您需要定义(若并没有定义的话)特殊的值,它将为您的对象扮演零的角色。