Blake Blake - 23 days ago 15
C++ Question

C++ Linked List

I am trying to create a Linked List to download a txt file and use the linked list to handle the file line by line. When handling the downloaded Linked List operations will be performed on it such as a text editor would.
I am encountering some problems however. It seems the "Node(string value)" section of the code has something wrong with it even though the original Node() declaration with no arguments passes. I am unable to figure out quite what it is.

Node.h

class Node
{
public:
Node();
Node(string value);
void setNext(Node *nextNode); // Allows the user to set where the "next" pointer of a node points

friend class LinkedList;
private:
string data; // Data box
Node* next; // Pointer box
};


Node.cpp

# include <string>
# include "Node.h"

using namespace std;

Node::Node()
{
data = "";
next = NULL;
}

Node::Node(string value)
{
data = value;
next = NULL;
}

void Node::setNext(Node *nextNode) // Allows the user to set where the "next" pointer of a node points
{
this->next = nextNode;
}

Answer

Your #include <string> should be in your header file since it is you are using the std::string type with your methods.

Since it is not recommended to add using namespace in header files (see this answer for more info), declare your string types with the namespace : change your string value to std::string value

Your files will look like this (compile test was done with GCC)

Also you should put an include guard in your header file

Example:

// some_header_file.h
#ifndef SOME_HEADER_FILE_H
#define SOME_HEADER_FILE_H
// your code
#endif

Node.h

#include <string>

class Node
{
public:
    Node();
    Node(std::string value);
    void setNext(Node *nextNode); // Allows the user to set where the "next" pointer of a node points

    friend class LinkedList;
private:
    std::string data; // Data box
    Node* next; // Pointer box
};

Node.cpp

#include "Node.h"
#include <cstddef>  // For NULL

Node::Node()
{
    data = "";
    next = NULL;
}

Node::Node(std::string value)
{
    data = value;
    next = NULL;
}

void Node::setNext(Node *nextNode) // Allows the user to set where the "next" pointer of a node points
{
    this->next = nextNode;
}
Comments