嘿,我创建了一个名为“节点”的抽象类和实现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;'将是该运算符的合法用法,尽管不是非常有用。你可能想要别的东西。 –