嘿,我创建了一个名为“ 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());
}
我删除了那些类的所有不必要的方法。现在我正在尝试重载<
但是我当前的输出是:
0x24f70e0
0x24f7130
0x24f7180
0x24f7340
0x24f7500
如您所知,这是地址。谢谢您的帮助
最佳答案
您要查找的是一个<<
运算符,该运算符的左侧为ostream
,右侧为Node
,并求值相同的ostream
。因此,应该这样定义(在Node
类之外):
std::ostream& operator<<(std::ostream& out, const Node& node) {
out << node.printValue();
return out;
}
然后,您需要确保正在
cout
而不是Node
:cout << *fast.top() << endl; // dereference the pointer
关于c++ - 字符串重载运算符“>>”,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40794725/