【发布时间】:2017-11-18 14:17:36
【问题描述】:
我正在尝试将包含字母“farming”的文本文件读入节点链接列表。我创建了一个名为 NumberList 的类,它具有节点的结构。这是标题。
#ifndef NUMBERLIST
#define NUMBERLIST
#include <iostream>
using namespace std;
class NumberList
{
protected:
//declare a class for the list node
//constructor to initialize nodes of list
struct ListNode
{
char value;
ListNode *next;
// Constructor
ListNode(char value1, ListNode *next1 = NULL)
{
value = value1;
next = next1;
}
};
ListNode *head; //pointer to head of the list
public:
NumberList() { head = NULL; } //constructor
~NumberList(); //destructor
void displayList() const; //print out list
void reverse();
};
#endif
我遇到的问题是尝试将文本文件读入 main() 中的链表。
这是我的主要内容:
#include "Numberlist.h"
#include "ReliableNumberList.h"
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ListNode *letterList = nullptr; //create a linked list
char letter;
//This is where I read the file into the list
//open the file
ifstream letterFile("linkedText.txt");
if (!letterFile)
{
cout << "Error in opening the file of letters.";
exit(1);
}
//read the file into a linked list
while (letterFile >> letter)
{
//create a node to hold this letter
letterList = new ListNode(letter, letterList);
//missing a move to the next node?
}
return 0;
}
这个读取文件示例来自我的教科书,但它读取的结构不在单独的类中。对于我的一生,我无法弄清楚我是如何在 NumberList 类中引用 ListNode 结构的。 Visual Studio 声明 ListNode 和 letterList 未定义。我知道这是因为我没有从 NumberList 类中正确引用它们。
任何帮助将不胜感激。
【问题讨论】:
-
欢迎来到 Stack Overflow。请花时间阅读The Tour 并参考Help Center 中的材料,您可以在这里问什么以及如何问。
-
ListNodestruct 似乎是来自外界的protected。这个想法可能是为了让NumberList有一个方法(我们称之为push_back(...))将chars 添加到内部(受保护/私有)列表中。这样NumberList对象将管理节点的创建和销毁,而在main()中,您只需编写漂亮的list.push_back(letter),而不是每次都直接创建ListNodes。 -
另外
ListNode实际上是NumberList::ListNode。ListNode在NumberList内。NumberList不必完全符合条件,因为它是NumberList。
标签: c++ pointers object linked-list member-function-pointers