节点和链接列表出现问题

Gre*_*t95 4 c++ static pointers private linked-list

我有一个任务,我应该创建在双向链表中插入和删除节点的方法.但是我的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
Run Code Online (Sandbox Code Playgroud)

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

}
Run Code Online (Sandbox Code Playgroud)

我得到的错误是:

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)
Run Code Online (Sandbox Code Playgroud)

如果我在cpp文件中引用静态时从私有变量中删除静态,我得到"非静态成员引用必须相对于特定对象"

And*_*ndy 9

你已成为frontrear成员static.这意味着LinkedList该类的所有实例只有这些成员的一个实例.

如果这是你想要的,那么你需要在.cpp文件中声明它们,就像@Soeren建议的那样:

node* LinkedList::front = nullptr;
node* LinkedList::read = nullptr;
Run Code Online (Sandbox Code Playgroud)

不过,你可能想要的是要创建多个能力LinkedListS,并保持轨道frontrear每一个.如果是这种情况,那么你应该使这些成员不是静态的(并且也使insert_front()非静态成员).

执行此操作时出错的原因是您需要创建该类的实例才能使用它:

LinkedList list;
list.insert_front(5);
Run Code Online (Sandbox Code Playgroud)


Soe*_*ren 6

您必须初始化cpp文件中的静态变量:

node* LinkedList::front = nullptr;
node* LinkedList::rear = nullptr;
Run Code Online (Sandbox Code Playgroud)

我们只能在类上调用静态类成员,而不能在类的对象上调用.即使没有实例,这也是可能的.这就是每个静态成员实例必须初始化的原因,通常是在cpp文件中.

并且由于静态变量在类范围之外初始化,我们必须通过全名调用变量(例如LinkedList :: front).