You haven't included the header that defines Node
.
Doubly linked node constructor in c++
-
06-10-2022 - |
Question
I am trying to make a node for a doubly linked list in c++, but experiencing some problems with the constructor. I have the following simplyfied header file:
class Node{
public:
Node();
private:
int data;
Node* next;
Node* previous;
};
My .cpp file looks as the following:
#include <iostream>
#include <cstdlib>
using namespace std;
int data;
Node* next;
Node* previous;
Node::Node(){
data = 0;
next = NULL;
previous = NULL;
}
I get the following error when compiling this: "Node does not name a type."
I have also tried to use 'struct' to create the Node:
struct Node{
int data;
Node* next;
Node* previous;
}
But this however gives me another error on the constructor in the cpp file: "definition of implicitly-declared ...."
How can I make this program compile without error messages by using a constructor and variables, and what am I doing wrong?
Solution
OTHER TIPS
You have to include the header with Node definition in your cpp module. Also I think these statements in the cpp module
int data;
Node* next;
Node* previous;
must be deleted.
You could define the constructor inside the class definition. I would define it as
class Node{
public:
Node( int data, Node *next = 0, Node *previous = 0 )
: data( data ), next( next ), previous( previous )
{
}
private:
int data;
Node* next;
Node* previous;
};