链表中C++专用指针错误
Private Pointer error in C++ linked list
我正在尝试在C++中实现链表,但每次编译时,我都会收到一个错误,说'Node* Node::nextPtr' is private
.如果我将nextPtr
更改为具有公共保护,那么我不会收到错误,并且我的列表很好。有人可以告诉我为什么会这样以及如何解决它吗?我的list
和node
课程如下:
//list.h
#include <string>
#include "node.h"
using namespace std;
class List
{
public:
List();
bool isEmpty();
void insertAtFront(string Word);
void displayList();
private:
Node * firstPtr;
Node * lastPtr;
};
//node.h
#ifndef NODE_H
#define NODE_H
#include <string>
using namespace std;
class Node
{
public:
Node(string arg);
string getData();
private:
string data;
Node * nextPtr;
};
//node.cpp
#include <iostream>
#include <string>
#include "node.h"
using namespace std;
Node::Node(string arg)
:nextPtr(0)
{
cout << "Node constructor is called" << endl;
data = arg;
}
string Node::getData()
{
return data;
}
//list.cpp
#include <iostream>
#include "list.h"
#include "node.h"
using namespace std;
List::List()
:firstPtr(0), lastPtr(0)
{
}
bool List::isEmpty()
{
if(firstPtr == lastPtr)
return true;
else
return false;
}
void List::displayList()
{
Node * currPtr = firstPtr;
do
{
if(currPtr->nextPtr == lastPtr) // Error here
cout << endl << currPtr->getData() << endl;
cout << endl << currPtr->getData() << endl;
currPtr = currPtr->nextPtr; //Error here
}
while(currPtr != lastPtr);
}
void List::insertAtFront(string Word)
{
Node * newPtr = new Node(Word);
if(this->isEmpty() == true)
{
firstPtr = newPtr;
cout << "Adding first element...." << endl;
}
else if(this->isEmpty() == false)
{
newPtr->nextPtr = firstPtr; //Error here
firstPtr = newPtr;
cout << "Adding another element...." << endl;
}
}
您没有在 List
类中显示成员函数的定义,但我敢打赌这是由于这些成员函数尝试从 Node 类访问nextPtr
。您可以
- 从
Node
公开nextPtr
- 将公共访问器函数添加到
Node
以访问它 - 宣布
List
为Node
的朋友,friend class List;
因为在代码中的某个地方,您可以通过类 Node
的非成员函数访问Node * nextPtr
。 您可以为nextPrt
创建一个getter
以避免这种情况。
相关文章:
- 为什么我在空指针错误(链表)中获取成员访问权限
- std::函数指针错误:无法将 &A::a 转换为类型 std::function<>&&
- 为什么我得到 munmap_chunk():无效的指针:错误
- 成员模板函数指针错误
- 删除指针时,未分配被释放的 C++ 指针错误
- Visual Studio 中的"指向引用的指针"错误不会按发生位置的文件名显示
- C++数组指针错误无法将“int*”转换为“int**”
- C++ 通过函数指针错误调用成员函数
- 从 BST 中删除元素(指针错误)
- 随机生成的多维布尔指针错误
- 在测试中使用unique_ptr时指针错误无效
- 使用 malloc 而不是 new 会导致 free():指针错误无效
- 非标准语法;使用 '&' 创建指向成员的指针错误,将成员函数分配给向量时出错
- 抽象类和唯一指针 c++ 错误
- 返回函数指针错误而不带类型定义
- 练习中出现空指针错误
- 指针错误导致的分段错误(简单..)
- free():C++中的指针错误无效
- 使用布尔值数组"表达式必须具有指向对象类型的指针"错误C++
- 指针错误的C 数组