c++ - 创建自己的链表时出错

标签 c++ linked-list singly-linked-list

我正在尝试创建一个从文本文件中读取并将单词存储到单链表中的程序。我应该创建自己的链表而不是使用 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/

相关文章:

c - 如何使用链接的实现在单链接列表中插入和删除元素

java - 递归地将节点添加到链表的末尾

c - 调试链表

c++ - 如何将 new 和 delete 与 OpenGL 的缓冲区对象一起使用?

c++ - 如何使用多项式类重载 operator+ 以及返回什么类型

c++ - 崩溃,同时打印链表的内容

c - GDB 中奇怪的崩溃错误

C 链表 - 令人惊叹的程序

c++ - 空指针算术

c++ - 无法将 C++ 与 Xcode 5 链接起来