2017-01-29 6 views
4

二重リンクされたリストのノードを挿入したり削除したりするためのメソッドを作成することになっています。しかし、私はC++で少し錆びています。 フロントポインタとリアポインタからエラーが発生しています。ノードとリンクされたリストの問題

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 
    //... 

} 

私は取得していますエラーは以下のとおりです。

unresolved external symbol "private: static struct node * LinkedList::front ([email protected]@@[email protected]@A) 


unresolved external symbol "private: static struct node * LinkedList::rear ([email protected]@@[email protected]@A) 

私はプライベート変数から静的を削除する場合私が参照するとき

node* LinkedList::front = nullptr; 
node* LinkedList::rear = nullptr; 

我々だけ呼び出すことができます静的クラス:あなたはあなたのcppファイル内の静的変数を初期化する必要があり、私は

答えて

9

frontrearのメンバーはstaticです。これは、LinkedListクラスのすべてのインスタンスに対して、これらのメンバーのインスタンスが1つだけ存在することを意味します。それはあなたが望むものである場合@Soerenが提案されているよう

は、あなたは、.cppファイルでそれらを宣言する必要があります:あなたはおそらく何をしたい

しかし
node* LinkedList::front = nullptr; 
node* LinkedList::read = nullptr; 

は、複数のLinkedListを作成する能力を持つことですそれぞれのfrontrearを追跡します。その場合、これらのメンバーを静的にしないでください(また、insert_front()も非静的にする必要があります)。

あなたがそれを使用するためには、クラスのインスタンスを作成する必要がありますので、あなたがこれを行うエラーの理由がある:

LinkedList list; 
list.insert_front(5); 
6

「非静的メンバ参照は、特定のオブジェクトに相対的でなければなりません」取得のcppファイルでそれらをレンスクラスのメンバーであり、クラスのオブジェクトではありません。インスタンスが存在しなくても可能です。そのため、すべての静的メンバーインスタンスは、通常はcppファイルでを初期化する必要があります。

静的変数がクラススコープ外で初期化されているため、変数をフルネーム(例:LinkedList :: front)で呼び出す必要があります。

関連する問題