节点和链表问题
Trouble with Nodes and Linked Lists
我有一个作业,我应该在其中创建方法来插入和删除双向链表中的节点。但是我对我的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 文件中引用私有变量时从私有变量中删除静态,我会得到"非静态成员引用必须相对于特定对象"
您已将front
和rear
成员设为static
。这意味着对于 LinkedList
类的所有实例,这些成员只有一个实例。
如果这是您想要的,那么您需要在.cpp文件中声明它们,如@Soeren建议的那样:
node* LinkedList::front = nullptr;
node* LinkedList::read = nullptr;
但是,您可能希望能够创建多个LinkedList
,并跟踪每个front
和rear
。如果是这种情况,那么您应该使这些成员不是静态的(同时也使insert_front()
非静态的)。
执行此操作时出错的原因是您需要创建类的实例才能使用它:
LinkedList list;
list.insert_front(5);
您必须初始化 cpp 文件中的静态变量:
node* LinkedList::front = nullptr;
node* LinkedList::rear = nullptr;
我们只能在类上调用静态类成员,而不能在类的对象上调用静态类成员。即使不存在实例,这也是可能的。这就是为什么每个静态成员实例都必须初始化的原因,通常在 cpp 文件中。
由于静态变量是在类范围之外初始化的,我们必须用全名来调用变量(例如 LinkedList::front)。
相关文章:
- 链表指针问题
- 我对数据结构、双向链表有一些问题
- 在解决链表问题时创建一个额外的节点是一个好习惯吗?
- Sinlge 链表,C++,删除所有和搜索功能的问题
- C++ 从链表中删除项目时出现问题
- 如何修复我的链表读数不一致的问题?
- C++中链表实现的问题
- 双向链表问题 - 包含项目但不显示
- 嵌套的类成员变量不可访问.链表设置.V、下一个和新的问题
- 在链表中的某个点插入时出现问题,C++中的继承函数
- cpp 中的以下链表程序有什么问题?
- 单个链表,节点插入最低到最高节点值的问题
- 我在让我的代码输出整个链表时遇到问题.它只是输出我修改过的一些文本文件,而不是整个东西
- 双向链表问题(特别是复制构造函数和删除函数)
- 我在双链表上的此打印功能时遇到问题
- 我在显示链表时遇到问题
- 尝试在链表程序的末尾进行更简单的插入.小问题需要帮助
- 节点和链表问题
- c++理解问题-链表和堆栈
- C++语法问题(链表)