2013-10-07 28 views
0

我想在C++中實現鏈接列表,但每次編譯時,都會收到一條說明'Node* Node::nextPtr' is private的錯誤。如果我更改nextPtr以獲得公共保護,那麼我不會收到錯誤消息,而且我的列表沒有問題。有人可以告訴我爲什麼這是和如何解決它?我listnode類如下所示: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;'就在'class Node {'聲明中。或者更好的是,考慮將'Node'作爲'class List'的私有嵌套類,即將它放在它所屬的位置。 – WhozCraig

+0

我在最後添加了兩個類的實現文件。 – rafafan2010

回答

1

您沒有在List類中顯示您的成員函數的定義,但我敢打賭是因爲這些成員函數試圖從Node類訪問nextPtr。您可以

  1. 使從Node
  2. nextPtr公共添加公共訪問函數來Node訪問它
  3. 聲明ListNode朋友,friend class List;
+0

謝謝!我使用'friend class List'方法來修復它。 – rafafan2010

1

因爲在某處你的代碼,您可以通過Node類非成員函數訪問Node * nextPtr。您可以爲nextPrt創建getter以避免這種情況。