数组结构需要无参数构造函数

Array struct requires parameterless constructor

本文关键字:参数 构造函数 结构 数组      更新时间:2023-10-16

我已经写了一个数组结构(是的,我知道它们已经存在于其他地方,但我想创建我自己的)。为什么我的代码要求我添加的项具有无参数构造函数?

template <typename T>
struct Array {
private:
    unsigned int Capacity;
    unsigned int Count;
public:
    T *Items;
    // ***********/
    Array()
    {
        Count = 0;
        Capacity = 0;
        Items = 0;
    }
    void resize(const unsigned int capacity)
    {
        Capacity = capacity;
        T *x = new T[Capacity];  //*** Error: invalid new-expression on class type SomeStruct ***//
        for (unsigned int i = 0; i < Count; i++)
            x[i] = Items[i];
        delete[] Items;
        Items = x;
    }
    void addItem(const T &item)
    {
        if(Count == Capacity)
            resize();
        Items[Count] = item;
        Count++;
    }
    ~Array() {
        delete[] Items;
    }
};

如果我创建一个这样的数组…

Array<SomeStruct> MyStructs;

…然后像这样调用resize()

MyStructs.resize(10);

…在显示的行中失败。

我以为我在数组上调用new,那么为什么它试图调用无参数构造函数?

指令T *x = new T[Capacity];创建Capacity类型为T的新对象,T的默认构造函数在此处被调用。这就是为什么你的类T需要一个默认的("无参数的")构造函数。

编辑:指令Items[Count] = item;需要赋值操作符或复制构造函数。如果两者都不可用,我猜编译器可能会执行成员克隆。