gpt4 book ai didi

c++ - 编译器错误C2541- 'delete' : delete : cannot delete objects that are not pointers

转载 作者:行者123 更新时间:2023-12-02 10:56:43 36 4
gpt4 key购买 nike

我写了这个课:

class StaticList
{
private:
int headFree;
int headList;
int locNew;
StaticListNode* listNodeArr;

public:
StaticList(int numberOfElements);
~StaticList();

void addToStaticList(int ComputerNum);
int getHeadList();
int getHeadFree();
StaticListNode* getListNodeArr();
void show() const;
};

然后进行动态分配:
StaticList::StaticList(int numberOfElements)
{
headFree = 1; //Because the first headFree is 1 (the 0 cell is dummy)
headList = -1;
locNew = -1;

this->listNodeArr = new StaticListNode[numberOfElements];

for (int i = 0; i < numberOfElements - 1; i++)
listNodeArr[i].setNext(i + 1);

listNodeArr[numberOfElements].setNext(-1);
}

The problem is that when I try to delete the allocation through the d'tor, it gives me the error:



enter image description here

可能是什么问题呢?我想念什么?

谢谢!

最佳答案

当您在数组中分配n个元素时,array[n]是您无法访问的地方。

当您调用deletedelete[]时,它想释放不是它的内存。

所以

listNodeArr[numberOfElements].setNext(-1);

StaticListNode类数组中的无效位置
更改为
listNodeArr[numberOfElements - 1].setNext(-1);

0numberOfElements之间的正确位置

关于c++ - 编译器错误C2541- 'delete' : delete : cannot delete objects that are not pointers,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61204248/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com