2016-11-24 134 views
0

嘿,我創建了一個名爲「節點」的抽象類和實現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」它將打印點的字符串。

,但我的電流輸出爲: 0x24f70e0 0x24f7130 0x24f7180 0x24f7340 0x24f7500

正如你知道的地址。感謝您的幫助

+1

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

+1

你現在需要一個'friend':) –

+0

'virtual string operator <<(const Node * node)const您正在定義一個運算符,其左側有一個節點,右側有一個節點指針,並返回一個字符串。像這樣的東西:'節點a;節點b;一個<<&b;'將是該運算符的合法用法,儘管不是非常有用。你可能想要別的東西。 –

回答

1

你要尋找的是一個<<操作是在左側的ostream和右側的Node,並評估相同的ostream。因此,應該像這樣(的Node類以外)來定義:

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

然後,你需要確保你cout荷蘭國際集團一Node,而不是一個Node*

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

當我定義自定義類時,你的意思是在課外,但在頭部內? – yairabr

+0

該函數必須位於全局範圍內,因此您需要在頭文件中聲明它的簽名並將實現放在源文件中。不管什麼頭文件/源文件,只要它們在合適的時候被包含在內,當然是 – qxz

+0

那麼你需要在'Node'的頭文件中聲明函數。你可以使函數'static'如果你真的想在頭文件中,或者只是將它放在任何源文件中。這並不重要;嘗試一下,看看你是否得到錯誤。 – qxz