2013-10-07 2 views
0

C++에서 연결된 목록을 구현하려고하지만 컴파일 할 때마다 'Node* Node::nextPtr' is private이라는 오류가 발생합니다. nextPtr을 공개 보호로 변경하면 오류가 발생하지 않고 내 목록이 정상입니다. 누군가 이것이 이것이 왜 그리고 어떻게 고칠 지 말해 줄 수 있습니까?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

당신이 우리의 라인을 보여줄 수, Node

  • 에서 nextPtr 대중
  • Node에서 친구로 List 선언에 액세스 할 수 Node 공공 접근 기능을 추가 할 수 있습니다 오류가있는 코드? – luiscubal

  • +0

    'class Node {'선언 안에'friend class List; 또는'Node'를'class List'의 private 중첩 클래스로 만드는 것을 고려해보십시오. 즉, 클래스가 속한 곳에 배치하십시오. – WhozCraig

    +0

    끝에 두 클래스의 구현 파일을 추가했습니다. – rafafan2010

    답변

    1

    List 클래스 안에 멤버 함수의 정의를 표시하지 않았지만 그 멤버 함수가 Node 클래스에서 nextPtr에 액세스하려고했기 때문입니다. 당신은

    1. friend class List;
    +0

    감사합니다! 나는 그것을 수정하기 위해'friend class List;'메소드를 사용했다. – rafafan2010

    1

    을 어딘가에 코드에서, 당신은 클래스 Node의 비 멤버 함수에 의해 Node * nextPtr에 액세스하기 때문에 다음과 같이 내 listnode 클래스입니다. 이를 피하기 위해 nextPrtgetter을 생성 할 수 있습니다.