[英]Private Pointer error in C++ linked list
I'm trying to implement a linked list in C++, but every time I compile, I get an error that says 'Node* Node::nextPtr' is private
. 我试图在C ++中实现一个链表,但是每次编译时,我都会收到一条错误消息,指出
'Node* Node::nextPtr' is private
。 If I change nextPtr
to have public protection, then I don't get the error and my list is fine. 如果我将
nextPtr
更改为具有公共保护,则不会收到此错误,并且列表很好。 Can someone tell me why this is and how to fix it? 谁能告诉我这是为什么以及如何解决? My
list
and node
classes are as follows: 我的
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;
}
}
Because somewhere in your code, you access Node * nextPtr
by non member functions of class Node
. 因为在某处你的代码,您可以访问
Node * nextPtr
通过类非成员函数Node
。 You can create a getter
for nextPrt
to avoid that. 您可以为
nextPrt
创建一个getter
来避免这种情况。
You didn't show the definitions of your member functions inside the List
class, but I bet it is due to those member functions try to access nextPtr
from the Node class. 您没有在
List
类中显示成员函数的定义,但是我敢打赌,这是由于这些成员函数试图从Node类访问nextPtr
。 You can, 您可以,
nextPtr
public from Node
Node
公开nextPtr
Node
to access it Node
添加公共访问器功能以对其进行访问 List
as a friend from Node
, friend class List;
Node
, friend class List;
声明List
为好友friend class List;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.