节点和链表问题

Trouble with Nodes and Linked Lists

本文关键字:问题 链表 节点      更新时间:2023-10-16

我有一个作业,我应该在其中创建方法来插入和删除双向链表中的节点。但是我对我的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

链接列表.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 (?front@LinkedList@@0PAUnode@@A)

unresolved external symbol "private: static struct node * LinkedList::rear (?rear@LinkedList@@0PAUnode@@A)

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

您已将frontrear成员设为static。这意味着对于 LinkedList 类的所有实例,这些成员只有一个实例。

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

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

但是,您可能希望能够创建多个LinkedList,并跟踪每个frontrear。如果是这种情况,那么您应该使这些成员不是静态的(同时也使insert_front()非静态的)。

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

LinkedList list;
list.insert_front(5);

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

node* LinkedList::front = nullptr;
node* LinkedList::rear = nullptr;
我们只能在类上调用静态类成员,

而不能在类的对象上调用静态类成员。即使不存在实例,这也是可能的。这就是为什么每个静态成员实例都必须初始化的原因,通常在 cpp 文件中。

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