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

时间:2012-03-18 16:37:25

标签: c++ class templates

我今天早些时候发布了关于模板类的文章,但是相当遥远,从这里得到了我之前问题的解决方案。当然,当这个问题得到解决时,总会有一个新的,我似乎无法弄清楚。

给出以下构造函数:

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

我想创建一个动态数组,然后我可以通过add-method插入任何类型的元素。来自main的调用将如下所示:

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

如何在构建数组时将数组初始化为零?我无法将对象设置为零;)

我以为我很聪明,并试图重载= -operator for 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;
};

以及以防万一:

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

4 个答案:

答案 0 :(得分:4)

将数组元素初始化为Type()。这是标准库容器的功能。对于内置数值类型,Type()等效于0.对于类/结构类型,Type()构造临时的默认构造对象。

答案 1 :(得分:2)

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

答案 2 :(得分:0)

只需将“向量”的每个元素(令人困惑的名称,顺便说一句,给定std::vector<>的突出性)分配给默认值。默认值只是Type(),因此您可以在构造函数体中执行以下操作:

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

答案 3 :(得分:0)

  

如何在构造数组时将数组初始化为零?我可以   没有将对象设置为零;)

您可以使用所谓的默认构造值。换句话说,您需要定义(如果未定义)特殊值,该特殊值将对您的对象起零作用。