我试图为 C++ 制作我自己的列表。我有这个类:
template <class T>
class List
{
private:
T *value, *valueHelper;
int valueSize;
public:
int size;
List()
{
valueSize = 2;
value = (T*)malloc(sizeof(T) * valueSize);
size = 0;
}
void Add(T val)
{
size++;
if (size > valueSize)
{
valueSize *= 2;
valueHelper = (T*)malloc(sizeof(T) * valueSize);
memcpy(valueHelper, value, sizeof(T) * (valueSize / 2));
free(value);
value = valueHelper;;
}
value[size - 1] = val;
}
T operator[](int P)
{
return value[P];
}
};
当我尝试主要使用它时,它对 Int 工作正常。Buy to Struct 有问题:
struct Material
{
string materialName;
int faceNum;
int meshNum;
Material(): materialName(""), faceNum(0), meshNum(0){};
};
void main()
{
List <Material> myList = List<Material>();
myList.Add(Material());
}
我在线上的类中遇到运行时错误:
value[size - 1] = val;
为什么?