For my small program, I need a class representing a node in an undirected graph. It looks like this:
#ifndef DIRECTED_GRAPH_NODE_H
#define DIRECTED_GRAPH_NODE_H
#include <cstdlib>
#include <string>
#include <ostream>
#include <unordered_set>
#include <utility>
class DirectedGraphNode;
class DirectedGraphNode {
private:
std::size_t m_id;
std::unordered_set<DirectedGraphNode*,
DirectedGraphNodeHasher,
DirectedGraphNodeEqualTo>* m_neighbors;
public:
DirectedGraphNode(std::size_t id)
: m_id{ id }
, m_neighbors{ new std::unordered_set<DirectedGraphNode*>} {}
std::unordered_set<DirectedGraphNode*,
DirectedGraphNodeHasher,
DirectedGraphNodeEqualTo>* getNeighbors() {
return m_neighbors;
}
void addNeighbor(DirectedGraphNode& neighbor) {
m_neighbors->insert(&neighbor);
}
bool operator==(DirectedGraphNode* other) {
return m_id == other->m_id;
}
friend std::ostream& operator<<(std::ostream&, const DirectedGraphNode&);
friend class DirectedGraphNodeHasher;
friend class DirectedGraphNodeEqualTo;
};
std::ostream& operator<<(std::ostream& os, const DirectedGraphNode& node) {
return os << "[DirectedGraphNode: id = " << node.m_id << "]";
}
struct DirectedGraphNodeHasher {
std::size_t operator()(const DirectedGraphNode*& node) const {
return node->m_id;
}
};
struct DirectedGraphNodeEqualTo {
bool operator()(const DirectedGraphNode*& node1, const DirectedGraphNode*& node2) const {
return node1->m_id == node2->m_id;
}
};
#endif // DIRECTED_GRAPH_NODE_H
The above gives me a plethora of error messages. I am clueless how to resolve this. I tried the following approaches:
class A;
class B {
private:
A* pa;
}
class A {
private:
B* pb;
}
and this:
class B;
class A {
private:
B* pb;;
}
class B {
private:
A* pa;
}
What comes to DirectedGraphNodeHasher and DirectedGraphNodeEqualTo, I need them in order for the actual graph nodes to play nicely with the std::unordered_set<DirectedGraphNode*>.
Needless to say, none of the above compiles. What am I doing wrong here?
.hfile and an implementation.cppfile, this solves some of the circular dependencies, but a better solution is to not have circular dependencies to begin with.;aside).