I have an assignment where I am supposed to create methods to insert and remove nodes in a doubly linked list. However I am a little rusty with my C++. I am getting an error from my front and rear pointers.
LinkedList.h
#ifndef LinkedList_h
#define LinkedList_h
#include <iostream>
using namespace std;
struct node {
node * prev;
int data;
node * next;
};
class LinkedList {
private:
//pointers to point to front and end of Linked List
static node * front; //the error is coming from here
static node * rear; //the error is coming from here
public:
static void insert_front(int data);
};
#endif
LinkedList.cpp
#include "LinkedList.h"
//insert int to front
void LinkedList::insert_front(int data) {
node *q = nullptr;
//If the list is empty
if (front == nullptr && rear == nullptr) {
q = new node;
q->prev = nullptr;
q->data = data;
q->next = nullptr;
front = q;
rear = q;
q = nullptr;
}
//If there is only one node in list
//...
//If there are at least 2 nodes in list
//...
}
The errors I am getting are:
unresolved external symbol "private: static struct node * LinkedList::front (?front@LinkedList@@0PAUnode@@A)
unresolved external symbol "private: static struct node * LinkedList::rear (?rear@LinkedList@@0PAUnode@@A)
if I remove static from the private variables when I reference them in the cpp file I get "a nonstatic member reference must be relative to a specific object"
You have made the front
and rear
members static
. This means that there is only one instance of these members for all instances of the LinkedList
class.
If that is what you want, then you need to declare them in the .cpp file, as @Soeren suggested:
node* LinkedList::front = nullptr;
node* LinkedList::read = nullptr;
However, what you probably want is to have the ability to create multiple LinkedList
s, and keep track of the front
and rear
of each. If that is the case, then you should make these members not static (and also make insert_front()
non-static as well).
The reason for the error when you do this is because you need to create an instance of the class in order to use it:
LinkedList list;
list.insert_front(5);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With