Reputation: 702
My question is about the inclusion of a typedef struct (or at least I think it is). It's probably silly but I couldn't figure out what's wrong with my code.
I have a Node.h
header that declares a class Node
:
class Node {
public:
Node(/*some parameters*/); // Class constructor
typedef struct{ // This represents a weighted edge of weight "weight" from the current node to another node "node"
Node* node;
double weight;
}EdgeInfo;
vector<EdgeInfo*> OutEdges; // This vector represents the outgoing weighted edges from this node
};
So I figured out that's the only place in my code I can declare the struct
because that's the only place where I can declare EdgeInfo
that "knows" what a Node
class object is.
Then I have a Graph.h
header, including the Node.h
file, that declares a Graph
class.
Now in the Graph.cpp
file I'm implementing a function that loops on all the outgoing edges of a Node
, more or less like this:
Node* current = /*passing an object of class Node*/
for(EdgeInfo* out : current->OutEdges){
/*working on the edges*/
}
The problem is that when I compile I get the error error: ‘EdgeInfo’ was not declared in this scope
at the for
loop.
As you probably can see I'm kind of a C++ newbie. I thought that by including Node.h
I could use the ´typedef struct` definitions inside the class the same way I use variables and functions. Am I wrong? Or didn't I understand how includes work in C++?
I hope I didn't miss any detail. Thank you so much for the help!
Upvotes: 2
Views: 831
Reputation: 971
"So I figured out that's the only place in my code I can declare the struct because that's the only place where I can declare EdgeInfo that "knows" what a Node class object is."
You could use a forward declaration. A another link: forward declaration, stackoverflow.
class Node; // forward declaration
struct EdgeInfo
{
Node* node; // now, `EdgeInfo` knows that a class named `Node` is defined somewhere.
double weight;
};
class Node {
public:
Node(/*some parameters*/); // Class constructor
vector<EdgeInfo*> OutEdges; // This vector represents the outgoing weighted edges from this node
};
Now when you include node.h
in graph.cpp
, or Graph.h
, it'll be aware about EdgeInfo
.
Upvotes: 2