gpt4 book ai didi

c++ - 为什么取消引用节点会破坏我的链表?

转载 作者:搜寻专家 更新时间:2023-10-30 23:59:26 26 4
gpt4 key购买 nike

所以我正在尝试用 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();

如果我改变我的 addgetNext函数返回 Node<T>*而不是 Node<T> ,它工作正常。但为什么取消引用会导致代码中断?我认为 .符号比 -> 更有意义,但我无法让它工作。我做错了什么?

最佳答案

现在您正在复制您添加的节点,而不是返回您创建的实际节点。括号只是为以后必须查看您的代码的其他人增加了一点清晰度。 add 函数需要改成这样:

Node<T>& add(T item) {
this->next = new Node(item);
return *(this->next);
}

或者您可以返回指向新创建的节点的指针,但这会使用 . 而不是 main 中的 -> 中断。

同样需要对next()

做类似的改动

关于c++ - 为什么取消引用节点会破坏我的链表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16465902/

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