gpt4 book ai didi

C++ 不通过其他方法保存更改

转载 作者:行者123 更新时间:2023-11-28 03:35:51 24 4
gpt4 key购买 nike

我正在尝试用 C++ 实现链表类,但遇到了问题。我有 += 运算符来添加新节点。

链表类接口(interface):

template <typename Type>

class LinkedList {
public:
LinkedList<Type>* head;
// linked list stracture
Type data;
LinkedList<Type>* next;
// others ....
size_t length;
public:
LinkedList();
~LinkedList();
void initializeHead(LinkedList<Type>* headPtr);
size_t size() const;
LinkedList& operator+=(const Type& add);
void operator-=(const Type& remove);
LinkedList<Type>& operator[] (const size_t index) const;
bool operator== (const LinkedList<Type> &versus) const;
friend ostream& operator<< (ostream& out,LinkedList& obj);
};

这里我有 += 重载工具:

template <typename Type> LinkedList<Type>& LinkedList<Type>::operator +=(const Type& add) {
// head ptr - :)
LinkedList<Type>* p = head->next;
// go to the end
while(p) p = p->next;
// now on end - create new..!!!
try {
p = new LinkedList<Type>;
} catch (bad_alloc& e) {
cout << "There\'s an allocation error....";
} catch (...) {
cout << "An unknown error.." << endl;
}// fill and done
p->data = add;
p->next = NULL;
// increment length .........
++head->length;
// done ............
return *p;
}

另外,我有“数组”访问重载方法:

template <typename Type> LinkedList<Type>& LinkedList<Type>::operator [](const size_t index) const {
if(index < 0 || index >= length) // invaild argument
throw exception();
// continue
LinkedList<Type>* p = head;
for(size_t i = 0; i < index; ++i) p = p->next; // we are at what we want
return *p;
}

一切正常 - 我检查了调试器,

问题是 - += 没有将新节点保存在“head->next”中,出于某种原因,在 finish += 方法之后,head->next 等于 null。

有人知道为什么新分配不链接到 head->next 吗?

非常感谢!!

最佳答案

while(p) p = p->next;之后p 为空

接下来你要做p = new LinkedList<Type>;但您不会将 p 链接到头部。

关于C++ 不通过其他方法保存更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10891815/

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