Frage

I'm trying to create a program that reads from a text file and stores the words into a singly linked list. I'm supposed to create my own linked list as opposed to using the STL. I've tried looking up a fair number of tutorials, but I keep getting an error on the variable "head." It says "a value type of Node cannot be used to initialize an entity of type Node"

This is 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);
        }

}

This is 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;
};

This is 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;
}

Under the actual List.cpp, it gives me an error when I say Node *temp = head; with the aforementioned error. Any reason why and how can I fix this?

War es hilfreich?

Lösung

Part of the problem here is that in List.cpp you've included Node.h twice.

  • directly includes List.h which itself includes Node.h
  • directly includes Node.h

I'm surprised that the compiler didn't warn you about this. It seems instead that it chose to redefine Node hence you end up with two Node values which aren't compatible. You need to add include guards to your header files to prevent double includes

List.h

#if !LIST_H
#define LIST_H
...
#endif

Node.h

#if !NODE_H
#define NODE_H
...
#endif

Also note that it's generally speaking considered bad practice to have using statements in header files. Instead use namespace qualified names in headers and put the using statements into the .cpp files.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top