Reputation: 45
I am trying to learn C++ and would like to implement some of the algorithms for finding minimum spanning trees in graphs. However, I am having some trouble writing the interface and I don't know where I am going wrong. I get two errors:
error: variable 'Graph::adjIterator it' has initializer but incomplete type
error: expected ',' or ';' before '=' token
graph.h
#ifndef GRAPH_H
#define GRAPH_H
#include<vector>
struct Edge {
int v, w;
double weight;
Edge(int v_, int w_, double weight_ = 1) :
v(v_), w(w_), weight(weight_) {
}
};
class Graph {
private:
int Vcnt, Ecnt;
bool directedGraph;
struct Node {
int v;
Node* next;
Node(int v_, Node* next_) :
v(v_), next(next_) {
}
};
std::vector<Node*> adj; //this is a linked list !
public:
Graph(int V, bool diGraph = false) :
adj(V), Vcnt(V), Ecnt(0), directedGraph(diGraph) {
adj.assign(V, NULL);
}
int V() {
return Vcnt;
}
int E() {
return Ecnt;
}
bool directed() const {
return directedGraph;
}
void insert(Edge e) {
int v = e.v;
int w = e.w;
adj[v] = new Node(w, adj[v]);
if (!directedGraph)
adj[w] = new Node(v, adj[w]);
Ecnt++;
}
bool egde(int v, int w) const;
//void remove(Edge e);
class adjIterator;
friend class adjIterator;
};
graph.cpp
#include "graph.h"
class Graph::adjIterator {
private:
const Graph & G;
int v;
Node* t;
public:
adjIterator(const Graph& G_, int v_) :
G(G_), v(v_) {
t = 0;
}
int begin() {
t = G.adj[v];
return t ? t->v : -1;
}
int nxt() {
if (t)
t = t->next;
return t ? t->v : -1;
}
bool end() {
return t == 0;
}
};
main.cpp
#include <iostream>
#include "graph.h"
int main() {
Graph G(2);
Edge e(0, 1);
G.insert(e);
for(Graph::adjIterator it(G,0) = it.begin(); it != it.end(); it.nxt()) {
//stuff
}
return 0;
}
Thanks in advance for your help.
Upvotes: 0
Views: 830
Reputation: 16582
You've defined the class 'adjIterator' in a .cpp file, and then tried to use it from a different .cpp file which has only seen the forward declaration in the .h
Also, while this isn't your immediate problem, you have a lot of stuff in your .h file that probably belongs in the .cpp.
Generally you put all your declarations in the .h, and all the implementation in a .cpp.
So a .h might have:
class myClass {
public:
myClass();
void someMethod(int argument);
}
And then the .cpp would have:
myClass::myClass()
{
//initialise stuff
}
void myClass::someMethod(int argument)
{
//do something clever
}
Upvotes: 2