我正在研究一個程序,該程序應該將文件的內容讀入鏈表以創建「hypercard堆棧」(我列出了具體的here)。我知道在C++標準庫中有一個列表類,但由於我以前從未使用過標準庫,我不知道如何使它適用於這個特定的問題。在C++中的類
以下是我通過將我所遇到的在線教程的各個部分拼湊在一起而設法實現的代碼。
我.h文件中:
//program6.h
#include <iostream>
#include <fstream>
#include <string>
#include <list>
using namespace std;
class Node {
public:
Node();
Node(char code, int num, string data);
Node(Node & node);
~Node();
bool readFile();
void setNext(Node* next);
void print();
private:
char Code;
int Num;
string Data;
Node *Next;
};
我實現文件:
//program6.cpp
#include "program6.h"
#include <iostream>
#include <fstream>
#include <list>
using namespace std;
Node::Node() {
Code = '\0';
Num = 0;
Data = "";
Next = NULL;
}
Node::Node(char code, int num, string data) {
Code = code;
Num = num;
Data = data;
Next = NULL;
}
Node::Node(Node & node) {
Code = node.Code;
Num = node.Num;
Data = node.Data;
Next = NULL;
}
Node::~Node() {
}
bool Node::readFile() {
char code = '\0';
int num = 0;
string data = "";
ifstream inputFile;
inputFile.open("prog6.dat");
if(!inputFile) {
cerr << "Open Faiulre" << endl;
exit(1);
return false;
}
Node *head = NULL;
while(!inputFile.eof()) {
inputFile >> code >> num >> data;
Node *temp = new Node(code, num, data);
temp->setNext(head);
head = temp;
}
inputFile.close();
head->print();
return true;
}
void Node::setNext(Node* next) {
Next = next;
}
void Node::print() {
cout << Code << " " << Num << " " << Data;
if(Next != NULL)
Next->print();
}
我的主/ test文件:
//program6test.cpp
#include "program6.h"
#include <iostream>
#include <fstream>
#include <list>
using namespace std;
int main() {
Node list;
if(list.readFile())
cout << "Success" << endl;
else
cout << "Failure" << endl;
return 0;
}
這裏是前述文件,我需要閱讀:
i 27 Mary had a little lamb
i 15 Today is a good day
i 35 Now is the time!
i 9 This lab is easy and fun
p
d 35
t
i 37 Better Now.
f
p
h
p
d 27
d 15
d 37
d 9
i 44 This should be it!
t
p
更新 感謝下面的答案,我能夠擺脫我最初得到的「未定義參考」錯誤,但是,這裏是我現在運行程序時得到的錯誤。
terminate called after throwing an instance of 'St9bad_alloc'
what(): St9bad_alloc
Aborted
另外請記住,雖然我得到一個錯誤,需要解決,這不是這個問題的主要目的。
對不起,如果這真的很廣泛,我不太瞭解這些,所以不知道如何進一步縮小範圍。任何人都可以幫助我弄清楚如何使用列表類來解決這個問題,再次,程序的細節可以在我在前面提供的鏈接中找到。
爲什麼當你已經在包含的.h文件中聲明它時,你在.cpp文件中聲明'Node'類? – Michael 2014-11-06 17:22:11
因爲我不知道我在做什麼。 – 2014-11-06 17:27:33
另外,你的'Node :: Node(char code,int num,string data)'構造函數將東西存儲到局部變量而不是對象成員。 – Michael 2014-11-06 17:27:34