c++ - 节点和链表的问题

标签 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 {

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 文件中引用它们时从私有(private)变量中删除静态,我会得到“非静态成员引用必须相对于特定对象”

最佳答案

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

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

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

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

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

LinkedList list;
list.insert_front(5);

关于c++ - 节点和链表的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41926112/

相关文章:

c++ - 对象成员的问题

c++ - 什么决定了调用 delete 时写入 C++ 指针的内容?

javascript - 将 javascript 日期设置为静态

c++ - 一次将反弹变量递增一个 - C++

c++ - 如何避免 PANTHEIOS_FE_PROCESS_IDENTITY 的多重定义?

c - 这两个函数指针声明有什么区别?

c# - 静态类的范围是什么?

django - Heroku 部署上的静态文件 Django

c++ - 用 C++ (OpenCV) 读取像素值

c++ - 验证取自 std::cin 的 char * 的长度