我正在尝试创建一个从文本文件中读取并将单词存储到单链表中的程序。我应该创建自己的链表而不是使用 STL。我已经尝试查找相当多的教程,但我总是在变量“head”上遇到错误。它说“Node 的值类型不能用于初始化 Node 类型的实体”
这是 List.cpp:
#include "List.h"
#include "Node.h"
#include <iostream>
using namespace std;
void List::add(string s){
Node* newNode = new Node();
newNode->addString(s);
newNode->setNext(NULL);
Node *temp = head;
if(temp != NULL)
{
while(temp->Next() != NULL)
{
temp = temp->Next();
}
temp->setNext(newNode);
}
else
{
head = newNode;
}
}
void List::print(){
Node *temp = head;
if(temp == NULL)
{
cout<<"EMPTY"<< endl;
return;
}
if(temp->Next() == NULL)
{
cout<<temp->Word();
cout<< "-->";
cout<< "NULL" << endl;
}
else
{ do{
cout<<temp->Word();
cout<<"-->";
temp = temp->Next();
}
while( temp != NULL);
cout << "NULL" << endl;
}
}
void List::read(ifstream& fin){
while(!fin.eof())
{
fin>>sTemp;
add(sTemp);
}
}
这是 Node.h
using namespace std;
#include <string>
class Node
{ string val;
Node* next;
public:
Node(void){}
Node(string s)
{
val = s;
next = nullptr;
}
void addString(string aString){ val = aString;};
void setNext(Node* aNext){next = aNext;};
string Word(){return val;};
Node* Next(){return next;};
string sTemp;
};
这是List.h
#include <string>
#include <fstream>
#include "Node.h"
using namespace std;
class List{
Node* head;
public:
List()
{
head = NULL;
}
void print();
void add(string s);
void find(string key);
void read(ifstream& fin);
string sTemp;
}
在实际的 List.cpp 下,当我说 Node *temp = head; 时它给我一个错误出现上述错误。任何原因以及我该如何解决这个问题?
最佳答案
部分问题在于,在 List.cpp
中,您包含了两次 Node.h
。
- 直接包含List.h,List.h本身包含Node.h
- 直接包含 Node.h
令我惊讶的是编译器没有就此警告您。相反,它似乎选择重新定义 Node
因此您最终得到两个不兼容的 Node
值。您需要在头文件中添加 include guard 以防止双重包含
列表.h
#if !LIST_H
#define LIST_H
...
#endif
节点.h
#if !NODE_H
#define NODE_H
...
#endif
另请注意,一般而言,在头文件中使用 using
语句被认为是不好的做法。而是在 header 中使用命名空间限定名称,并将 using
语句放入 .cpp 文件中。
关于c++ - 创建自己的链表时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21946127/