Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 节点和链接列表有问题_C++_Pointers_Static_Linked List_Private - Fatal编程技术网

C++ 节点和链接列表有问题

C++ 节点和链接列表有问题,c++,pointers,static,linked-list,private,C++,Pointers,Static,Linked List,Private,我有一个任务,我应该在其中创建方法来插入和删除双链接列表中的节点。不过,我的C++有点生疏了。 我的前后指针出现错误 LinkedList.h #ifndef LinkedList_h #define LinkedList_h #include <iostream> using namespace std; struct node { node * prev; int data; node * next; }; class LinkedList {

我有一个任务,我应该在其中创建方法来插入和删除双链接列表中的节点。不过,我的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
我得到的错误是:

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)

如果我在cpp文件中引用私有变量时删除了静态变量,我会得到“非静态成员引用必须与特定对象相关”

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

node* LinkedList::front = nullptr;
node* LinkedList::rear = nullptr;
我们只能在类上调用静态类成员,而不能在类的对象上调用。这是可能的,即使不存在实例。这就是为什么每个静态成员实例必须初始化的原因,通常在cpp文件中


由于静态变量是在类范围外初始化的,因此我们必须按全名调用该变量(例如LinkedList::front)。

您已经创建了
前部
后部
成员
静态
。这意味着对于
LinkedList
类的所有实例,这些成员只有一个实例

如果这是您想要的,那么您需要在.cpp文件中声明它们,正如@Soeren所建议的:

node* LinkedList::front = nullptr;
node* LinkedList::read = nullptr;
但是,您可能希望能够创建多个
链接列表
s,并跟踪每个链接列表的
前部
后部
。如果是这种情况,那么您应该使这些成员不是静态的(同时也使
insert\u front()
非静态)

执行此操作时出现错误的原因是,为了使用该类,需要创建该类的实例:

LinkedList list;
list.insert_front(5);
LinkedList list;
list.insert_front(5);