嘿,我創建了一個名爲「節點」的抽象類和實現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
正如你知道的地址。感謝您的幫助
見本:http://stackoverflow.com/questions/476272/how-to-properly-overload-the-operator-for-an-ostream – qxz
你現在需要一個'friend':) –
'virtual string operator <<(const Node * node)const您正在定義一個運算符,其左側有一個節點,右側有一個節點指針,並返回一個字符串。像這樣的東西:'節點a;節點b;一個<<&b;'將是該運算符的合法用法,儘管不是非常有用。你可能想要別的東西。 –