C ++链表中的私有指针错误

时间:2013-10-07 21:41:35

标签: c++ linked-list

我正在尝试在C ++中实现链接列表,但每次编译时,都会收到'Node* Node::nextPtr' is private的错误消息。如果我更改nextPtr以获得公共保护,那么我不会收到错误,我的列表也没问题。有人可以告诉我为什么这是以及如何解决它?我的listnode课程如下:

//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;
    }
}

2 个答案:

答案 0 :(得分:1)

因为代码中的某个位置,您可以通过类Node * nextPtr的非成员函数访问Node。您可以为getter创建nextPrt以避免这种情况。

答案 1 :(得分:1)

您没有在List类中显示您的成员函数的定义,但我敢打赌,这是由于这些成员函数尝试从Node类访问nextPtr。你可以,

  1. nextPtr
  2. 公开Node
  3. 将公共访问者功能添加到Node以访问它
  4. 将来自ListNode
  5. 的朋友声明为friend class List;