引用返回空值



我正在写一个链表,并使用我的main函数来测试它。下面是我的代码:

#include <iostream>
using namespace std;
class LinkedList {
int value;
LinkedList* next;
public:
LinkedList(int valueIn, LinkedList* nextIn) {
value = valueIn;
next = nextIn;
}
LinkedList(int valueIn) {
value = valueIn;
}
int getValue() {
return value;
}
void addNode(LinkedList* node) {
next = node;
}
LinkedList& getNext() {
return *next;
}
};
int main() {
cout << "starting..." << std::endl;
LinkedList list1(1);
LinkedList list2(2, &list1);
cout << list1.getValue() << " --> " << list1.getNext().getValue() << std::endl;
return 0;
}

我期望输出是1 --> 2,但我得到的是1 -->。据我所知,getNext()应该返回对另一个列表的引用(在本例中为list2),但似乎有些问题。我的调试工作表明,list2在初始化时确实具有正确的value2,但是当它被引用用于最终输出时,它似乎没有value的任何内容。我怎么也想不明白这是为什么。有人能帮我理解一下吗?

您将list1(实际上是一个节点)插入到list2的末尾,而不是反过来,但是您在list1上调用getNext()。您应该将main中的代码更改为以下内容:

int main() {
std::cout << "starting..." << std::endl;
LinkedList list1(1);
LinkedList list2(2, &list1);
std::cout << list2.getValue() << " --> " << list2.getNext().getValue() << std::endl;
return 0;
}

请注意,还有一些地方需要修改:

  1. 创建一个list类和Node类会让事情更清楚
  2. LinkedList(int valueIn)构造函数中将指针初始化为NULL(或c++ 11中的nullptr)
  3. 将指针返回到getNext()中的节点,而不是复制节点

您没有得到一个空白值。实际上,当您试图调用list1.getNext().getValue()时,您的程序正在崩溃,因为getNext()正在返回对NULL的引用。

你正在做与你想做的相反的事情。您的list2指向list1,list1指向NULL

你应该这样修改你的代码:

LinkedList list2(2);
LinkedList list1(1, &list2);
cout << list1.getValue() << " --> " << list1.getNext().getValue() << std::endl;