图形实现:变量具有初始值设定项,但类型不完整

graph implementation: variable has initializer but incomplete type

本文关键字:类型 变量 实现 图形      更新时间:2023-10-16

我正在尝试学习C++,并希望实现一些算法来查找图中的最小生成树。但是,我在编写界面时遇到了一些问题,我不知道哪里出了问题。我得到两个错误:

错误:变量"图形::adjIterator iterator"具有初始值设定项,但类型不完整

错误:在"="标记之前应使用","或";"

图形.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;
};

图形.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;
    }
};

主.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;
}

提前感谢您的帮助。

您已经在.cpp文件中定义了类"adjIterator",然后尝试从另一个.cpp文件中使用它,该文件仅在.h中看到前向声明

此外,虽然这不是您的直接问题,但您的 .h 文件中有很多可能属于.cpp的东西。

通常,您将所有声明放在 .h 中,将所有实现放在一个.cpp中。

所以一个.h可能有:

class myClass {
  public:
  myClass();
  void someMethod(int argument);
}

然后.cpp将具有:

myClass::myClass()
{
  //initialise stuff
}
void myClass::someMethod(int argument)
{
  //do something clever
}