【问题标题】:Trouble with Nodes and Linked Lists节点和链表的问题
【发布时间】:2017-06-15 00:46:19
【问题描述】:

我有一个任务,我应该在其中创建在双向链表中插入和删除节点的方法。但是我对我的 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 (?front@LinkedList@@0PAUnode@@A)


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

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

【问题讨论】:

    标签: c++ pointers static linked-list private


    【解决方案1】:

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

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

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

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

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

    LinkedList list;
    list.insert_front(5);
    

    【讨论】:

      【解决方案2】:

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

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

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-05-05
        • 2014-09-13
        • 1970-01-01
        • 1970-01-01
        • 2020-03-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多