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++ - 除非存在 libstdc++-6.dll,否则使用命令行命令或通过 VS Code 编译 C++ 程序无法正常运行

c++ - 优先使用带有大小模板的方法而不是带有指针类型的方法

c - 遍历链表时的段错误

c - C中链表的总大小

c - 如何在c中声明单链表?

c - 添加到列表功能

c++ - 在 VS2010 中为平台工具集 v90 构建 C++ CLR 应用需要 Visual Studio 2008

C++:为什么代码正在编译

go - 在 Go 语言中返回其结构地址的方法

java - 单链表上的双向迭代