为什么解引用节点会破坏我的链表
Why does dereferencing nodes break my linked-list?
所以我试图实现一个运行的工厂链表在c++
template<class T>
class Node
{
private:
Node *next;
T item;
public:
Node(T item)
: item(item)
{
this->next = NULL;
}
Node<T> add(T item) {
this->next = new Node(item);
return *this->next;
}
bool hasNext()
{
return this->next == NULL;
}
Node<T> getNext()
{
return *this->next;
}
T value()
{
return this->item;
}
};
void main()
{
Node<int> node(3);
node.add(3).add(4);
cout << node.value();
cout << node.getNext().value();
cout << node.getNext().getNext().value();
cin.get();
}
但是我不能让它工作。特别是这一节:
node.add(3).add(4);
cout << node.value();
cout << node.getNext().value();
cout << node.getNext().getNext().value();
如果我改变我的add
和getNext
函数返回Node<T>*
而不是Node<T>
,它工作得很好。但是为什么解引用会导致代码中断呢?我认为.
符号比->
更有意义,但我不能让它工作。我做错了什么?
现在您正在复制您添加的节点,而不是返回您创建的实际节点。括号只是为稍后必须查看您的代码的其他人增加了一点清晰度。add函数需要这样修改:
Node<T>& add(T item) {
this->next = new Node(item);
return *(this->next);
}
或者您可以返回一个指向新创建节点的指针,但是这会破坏在main中使用.
而不是->
。
同样需要对next()
相关文章:
- 我的链表没有按预期打印出来?
- 使用 valgrind 检查我的链表暗示中的内存泄漏,让我"肯定丢失:1 个块中有 40 个字节"
- 如何修复我的链表读数不一致的问题?
- C++:我的链表尾巴没有改变?我似乎无法让节点正确指向彼此?
- 如何使我的链表在C++中向后打印
- 为什么我无法显示我的链表?
- 如何在用于删除节点的函数中检查我的链表是否C++为空
- 虽然循环在我的链表中不起作用
- 为什么一个循环需要电流>链接 !=NULL 和一个电流 != NULL 作为我的链表?
- 什么错误的逻辑导致我的链表的这个 push_back(..) 函数失败?
- 为什么我的链表"next"指针取消引用错误的内存(XCode,C++)
- 我的链表实现是否泄漏内存
- 试图理解我的链表程序中的内存泄漏
- 为什么我的链表的复制构造函数总是出现分段错误
- 为什么我的析构函数导致我的链表出现问题
- 有人可以告诉我为什么从我的链表中打印垃圾
- 在我的链表实现中,我对 std::shared_ptr 和 std::unique_ptr 做错了什么
- 数据类型匹配,但我的链表仍然出错
- 我的链表代码有错误,有人能帮我检查哪里错了吗
- 为什么解引用节点会破坏我的链表