2016-11-24 25 views
0

"Node"という抽象クラスと、Nodeクラスを実装する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の内側に、これはメインクラスのための私のコードの一部である値を印刷する必要があります

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()); 
} 

私はそれらのクラスのすべての不要なメソッドを削除しました。今私は< <演算子をオーバーロードしようとしているので、スタックからiを上にして "cout"に割り当てると、ポイントの文字列が出力されます。

が、私の現在の出力は次のようになります。 0x24f70e0 0x24f7130 0x24f7180 0x24f7340 0x24f7500

あなたがアドレスである知っています。助けあなたが探しているもの

+1

これを参照してください。したがって、この(Nodeクラスの外)のように定義されるべきです:http://stackoverflow.com/questions/476272/how-to-properly-overload-the-operator-for-an-ostream – qxz

+1

あなたは今、 'friend'を必要としています:) –

+0

' virtual string operator <<(constノード*ノード)const'左にノードがあり、右にノードポインタを持ち、文字列を返す演算子を定義しています。このようなもの: 'Node a;ノードb; a&b;はこの演算子を法的に使用しますが、あまり有用ではありません。あなたはおそらく他の何かをしたいでしょう。 –

答えて

1

ためのおかげで、右に左とNodeostreamを持っており、同じostreamに評価<<演算子です。

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

その後、あなたはcoutNode、ないNode*をINGのしていることを確認する必要があります:

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

私はカスタムクラスを定義するとき、あなたはクラスの外ではなくヘッダの内側にあるのですか? – yairabr

+0

その関数はグローバルスコープになければなりません。そのため、ヘッダーにシグネチャを宣言し、実装をソースファイルに入れる必要があります。適切なときにインクルードされているかぎり、どのヘッダ/ソースファイルでも問題はありません。 – qxz

+0

'Node'が入っているどのヘッダでも関数を宣言したいと思うでしょう。あなたが本当にそれをヘッダーに入れたいのであれば、それを任意のソースファイルに投げるだけです。それは本当に問題ではありません。それを試して、エラーが出るかどうかを確認してください。 – qxz

関連する問題