2013-10-07 5 views
0

Я пытаюсь реализовать связанный список на C++, но каждый раз, когда я компилирую, я получаю сообщение об ошибке 'Node* Node::nextPtr' is private. Если я изменю nextPtr, чтобы иметь общедоступную защиту, тогда я не получу ошибку, и мой список в порядке. Может кто-нибудь сказать мне, почему это и как это исправить? Мои list и node следующие классы:Ошибка частного указателя в C++ связанном списке

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

Не могли бы вы показать нам линию код с ошибкой? – luiscubal

+0

drop 'friend class List;' просто внутри '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' ' Или еще лучше подумайте о том, чтобы сделать 'Node' частным вложенным классом класса List, т. Е. Поставить его там, где он принадлежит. – WhozCraig

+0

Я добавил файлы реализации для двух классов в конце. – rafafan2010

ответ

1

Вы не указали определения своих функций-членов внутри класса List, но я уверен, что из-за того, что эти функции-члены пытаются получить доступ к nextPtr из класса Node. Вы можете,

  1. сделать nextPtr общественности от Node
  2. добавить функции общественных аксессоры к Node для доступа к нему
  3. объявить List как друг от Node, friend class List;
+0

Спасибо! Я использовал метод «Список классов друзей», чтобы исправить его. – rafafan2010

1

Потому что где-то в вашем коде, вы получаете доступ Node * nextPtr не являющимися функциями-членами класса Node. Вы можете создать getter для nextPrt, чтобы избежать этого.

Смежные вопросы