yairabr yairabr - 15 days ago 7
C++ Question

string overloading operator ">>"

hey i created an abstract class called "Node" and and class NodeBlock that implements the Node class. in my main class i need to print the values that inside the NodeBlock this is some of my code for the main class:

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


Node:

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





i deleted all the unnecessary method of those class. now i'm trying to overload the << operator so when i top.() from the stack it will and assign it to the "cout" it will print the string of the point.

but my current output is:
0x24f70e0
0x24f7130
0x24f7180
0x24f7340
0x24f7500

which as you know is the address. thanks for the help

qxz qxz
Answer

What you're looking for is a << operator that has an ostream on the left and a Node on the right, and evaluates to the same ostream. Thus, it should be defined like this (outside of the Node class):

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

Then you need to make sure that you're couting a Node, not a Node*:

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