我試圖將包含字母「farming」的文本文件讀入鏈接的節點列表。我創建了一個名爲NumberList的類,它具有節點的結構。這是標題。將文件讀入鏈接列表在一個類中使用節點結構的C++
#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](http://stackoverflow.com/tour),並參閱[幫助中心](http://stackoverflow.com/help/asking)中的資料,瞭解您可以在這裏問。 –
'ListNode'結構似乎被外界「保護」。這個想法很可能是因爲'NumberList'會有一個方法(讓我們稱之爲'push_back(...)')來將'char'添加到內部(protected/private)列表中。這樣'NumberList'對象可以管理節點的創建和銷燬,而在'main()'中,你將只需要編寫很漂亮的'list.push_back(letter)',而不是每次都直接創建'ListNode's。 – Drop
另外'ListNode'實際上是'NumberList :: ListNode'。 'ListNode'在'NumberList'裏面。 'NumberList'不必完全限定,因爲它是'NumberList'。 – user4581301