2016-11-24 1 views
0

안녕하세요 "Node"라는 추상 클래스와 Node 클래스를 구현하는 NodeBlock 클래스를 만들었습니다. 내 메인 클래스에서 나는 NodeBlock 안에이이 값을 인쇄하는 데 필요한 기본 클래스에 대한 내 코드의 일부 :문자열 오버로딩 연산자 ">>"

//receving the fasteset route using the BFS algorithm. 
std::stack<Node *> fast = bfs.breadthFirstSearch(start, goal); 

/*print the route*/ 
while (!fast.empty()) { 
    cout << fast.top() << endl; 
    fast.pop(); 
} 

노드 :

#include <vector> 
#include "Point.h" 
#include <string> 

using namespace std; 

/** 
* An abstract class that represent Node/Vertex of a graph the node 
* has functionality that let use him for calculating route print the 
* value it holds. etc.. 
*/ 
    class Node { 
    protected: 
     vector<Node*> children; 
     bool visited; 
     Node* father; 
     int distance; 

    public: 
     /** 
     * prints the value that the node holds. 
     */ 
     virtual string printValue() const = 0; 

     /** 
     * overloading method. 
     */ 
     virtual string operator<<(const Node *node) const { 
      return printValue(); 
     }; 

    }; 

NodeBlock.h :

#ifndef ADPROG1_1_NODEBLOCK_H 
#define ADPROG1_1_NODEBLOCK_H 

#include "Node.h" 
#include "Point.h" 
#include <string> 


/** 
* 
*/ 
class NodeBlock : public Node { 
private: 
    Point point; 

public:  
    /** 
    * prints the vaule that the node holds. 
    */ 
    ostream printValue() const override ; 
}; 
#endif //ADPROG1_1_NODEBLOCK_H 

NodeBlock.cpp :

#include "NodeBlock.h" 
using namespace std; 



NodeBlock::NodeBlock(Point point) : point(point) {} 

string NodeBlock::printValue() const { 
    return "(" + to_string(point.getX()) + ", " + to_string(point.getY()); 
} 

나는 이러한 클래스의 모든 불필요한 메소드를 삭제했습니다. 이제 < < 연산자를 오버로드하려고합니다. 스택에서 최상위 비트 (.)를 가져오고 "cout"에 할당하면 점의 문자열이 인쇄됩니다.

하지만 내 전류 출력은 다음과 같습니다 당신이 주소 알고 0x24f7500

0x24f70e0 0x24f7130 0x24f7180 0x24f7340. 당신이 찾고있는 어떤 도움

+1

이보기 : http://stackoverflow.com/questions/476272/how-to-properly-overload-the-operator-for-an-ostream – qxz

+1

지금 '친구'가 필요합니다 :) –

+0

'가상 문자열 연산자 << (const 노드 * 노드) const' 왼쪽에 노드가 있고 오른쪽에 노드 포인터가있는 연산자를 정의하고 문자열을 반환합니다. 이것과 같은 것 :'Node a; 노드 b; <<< 및 b;는 몹시 유용하지는 않지만이 연산자를 합법적으로 사용합니다. 당신은 아마 다른 것을 원할 것입니다. –

답변

1

에 대한 감사 왼쪽에 ostream 오른쪽에 Node이있는 << 운영자이며, 같은 ostream로 평가합니다. 따라서,이합니다 (Node 클래스의 외부)과 같이 정의한다 :

std::ostream& operator<<(std::ostream& out, const Node& node) { 
    out << node.printValue(); 
    return out; 
} 

그런 다음 당신은 당신이 coutNode을 보내고있어 있는지 확인해야 아닌 Node* :

cout << *fast.top() << endl; // dereference the pointer 
+0

사용자 정의 클래스를 정의 할 때 클래스 외부에 있지만 헤더 내부에있는 것을 의미합니까? – yairabr

+0

그 함수는 전역 범위에 있어야하므로 헤더에 시그니처를 선언하고 구현을 소스 파일에 넣어야합니다. 적절할 때 어떤 헤더/소스 파일이 포함되어있는 지 상관하지 않습니다. – qxz

+0

그럼 Node에있는 어떤 헤더에서든 함수를 선언하고 싶습니다. 함수를 static으로 만들 수 있습니다. 당신이 정말로 헤더에 그것을 원한다면, 아니면 그냥 모든 소스 파일에 던져. 별로 중요하지 않습니다. 그것을 밖으로 시도하고 오류가 있는지 여부를 참조하십시오. – qxz