【发布时间】:2010-10-06 13:44:00
【问题描述】:
全部!我不知道“覆盖”是否是正确的词。在我的 编程类,我要创建一个循环列表,这样每个节点 node 包含一个指向下一个节点和最后一个节点的指针 指向第一个节点。此外,还有一个尾节点指向 添加的最后一个节点(在添加任何节点之前为 null)。
我无法填充我的列表(称为响铃),因为每次我调用 Ring::Insert(const int& d) 函数,插入单个节点,它 到达“RingNode newNode(d);”行,新的 RingNode 对象 覆盖我上次创建的上一个 RingNode 对象 称为 Ring::Insert(const int& d) 函数。很明显,我不想 这是因为它弄乱了我的清单。每次我如何做到这一点 函数创建一个全新的 RingNode 对象,它不会干扰 以前的 RingNode 对象?
我的头文件中的源代码,以防万一:
class RingNode {
public:
RingNode(const int& i=0 ): data(i), next(NULL){}
private:
int data; /* ID of player */
RingNode* next;
friend class Ring;
这是有问题的功能
RingNode* Ring::Insert(const int& d){
RingNode newNode(d); //This line overwrites previous RingNode objects
RingNode* refNode = &newNode; //Probably bad form, but that's not my main concern right now
if (tail==null){
tail = refNode;
newNode.next = refNode;
return refNode;
}
newNode.next = (*GetTail()).next;
(*GetTail()).next = refNode;
tail = refNode;
return refNode;
}
因此,例如,如果我在我的 main 中执行以下 sn-p...
Ring theRing;
theRing.Insert(5);
theRing.Insert(2);
theRing.Insert(7);
如果我调试我的项目,我可以看到 theRing 只包含一个 RingNode, 首先是 5 RingNode,然后是 2 RingNode 覆盖它,然后是 7 RingNode 会覆盖它。感谢您的阅读并再次感谢您的 回复!
编辑:我替换了
RingNode newNode(d);
RingNode* refNode = &newNode;
与
RingNode *newNode = new RingNode(d);
调整了其余的代码,它工作正常。非常感谢你们的帮助,伙计们!非常有用,最重要的是我现在明白了为什么它搞砸了。
【问题讨论】:
-
请务必接受您的问题的答案。