C++ 创建自己的链接列表时出错
我正在尝试创建一个程序,从文本文件中读取单词并将其存储到单个链接列表中。我应该创建自己的链表,而不是使用STL。我试着查找了大量教程,但变量“head”上不断出现错误。它说“节点的值类型不能用于初始化节点类型的实体” 这是List.cpp:C++ 创建自己的链接列表时出错,c++,linked-list,singly-linked-list,C++,Linked List,Singly Linked List,我正在尝试创建一个程序,从文本文件中读取单词并将其存储到单个链接列表中。我应该创建自己的链表,而不是使用STL。我试着查找了大量教程,但变量“head”上不断出现错误。它说“节点的值类型不能用于初始化节点类型的实体” 这是List.cpp: #include "List.h" #include "Node.h" #include <iostream> using namespace std; void List::add(string s){ Node* newNode =
#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);
}
}
#包括“List.h”
#包括“Node.h”
#包括
使用名称空间std;
无效列表::添加(字符串s){
Node*newNode=newNode();
新建节点->添加字符串;
新建节点->设置下一步(空);
节点*温度=头部;
如果(温度!=NULL)
{
while(临时->下一步()!=NULL)
{
temp=temp->Next();
}
temp->setNext(新节点);
}
其他的
{
头=新节点;
}
}
作废列表::打印(){
节点*温度=头部;
if(temp==NULL)
{
这里的部分问题是,在List.cpp
中,您已经包含了Node.h
两次
- 直接包括List.h,其本身包括Node.h
- 直接包括Node.h
我很惊讶编译器没有警告您这一点。相反,它似乎选择了重新定义节点
,因此您最终得到了两个不兼容的节点
值。您需要在头文件中添加包含保护以防止双重包含
清单h
#if !LIST_H
#define LIST_H
...
#endif
Node.h
#if !NODE_H
#define NODE_H
...
#endif
还请注意,通常认为在头文件中使用语句是不好的做法。相反,在头文件中使用名称空间限定名,并将使用语句放入.cpp文件中。谢谢!因此{using}属于.cpp文件,而不是.h文件。明白了!
#if !LIST_H
#define LIST_H
...
#endif
#if !NODE_H
#define NODE_H
...
#endif