面向对象编程(OOP)类定义问题

3

我正在做C++的作业,遇到了一些关于多重定义的问题。

我的图形类:

 class Graph{

     private:
          string name;                          //Graph name
          fstream* graphFile;                   //Graph's file

  protected:
    string opBuf;                         //Operations buffer
          int containsNode(string);             //Query if a node is present    
          Node* nodes;                          //Nodes in the graph
          int nofNodes;                         //Number of nodes in the graph

  public:
          static int nOfGraphs;                 //Number of graphs produced

          Graph();                              //Constructors and destructor
          Graph(int);
          Graph(string);
          Graph(const Graph &);
          ~Graph();

          string getGraphName();                //Get graph name
          bool addNode(string);                 //add a node to the graph
          bool deleteNode(string);              //delete a node from the graph
          bool addEdge(string,string);          //add an edge to the graph
          bool deleteEdge(string,string);       //delete an edge from the graph
          void intersect(const Graph&);         //intersect the graph with the <par>
          void unite(const Graph&);             //intersect the graph with the <par>
          string toString();                    //get string representation of the graph
       void acceptTraverse(BreadthFirst*);
    void acceptTraverse(DepthFirst *);


};

和我的遍历类一起;
 class Traversal {
public:
 string *visitedNodes;

 virtual string traverse (const Graph & );
};

class BreadthFirst  : public Traversal {
public :
 BreadthFirst();
 string traverse();
};

class DepthFirst : public Traversal {
public :
 DepthFirst();
 string traverse();
};

我的问题出现在遍历类中,我需要同时声明图形类,在图形类中我需要遍历类来声明。

我在声明方面遇到了很大的问题:) 你能帮我吗?


1
我只想说,你真的不需要以这种方式注释代码。每行代码都应该是自解释的,在你的情况下我认为确实如此,所以你真的不需要复制信息。相反,你应该注释决策,例如你使用了基于节点对象的图形实现(而不是基于边缘对象或基于边缘矩阵的实现)。 - Gabriel Ščerbák
4个回答

2
提前声明会有所帮助,可以考虑只执行acceptTraverse(Traversal*)方法。访问者模式可能会对您有所帮助。请参考访问者模式

1
如果我理解正确,我尝试了这个;
图形类中,在图形类声明之前,我添加了
class BreadthFirst;
class DepthFirst;

traversal.cpp 文件中,我使用了以下代码;

#include "Graph.h"
#include "Traversal.h"

通过这个,很多问题都解决了,但现在还有一个问题;

错误 8 错误 LNK2001: 无法解析的外部符号 "public: virtual class std::basic_string,class std::allocator > __thiscall Traversal::traverse(class Graph const&)" (?traverse@Traversal@@UAE?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@ABVGraph@@@Z) & nbsp; c:\Users\oben isik\documents\visual studio 2010\Projects\hw2\hw2\main.obj

错误 9 错误 LNK1120: 1 个无法解析的外部命令 c:\users\oben isik\documents\visual studio 2010\Projects\hw2\Debug\hw2.exe 1

我现在该怎么办?


0

不需要类的定义,只需要向编译器提示GraphTraversal是类。因此,在Graph的定义中(即在class Graph{...}上面)使用forward declartion,例如class BreadthFirst;。同样,在 Traversal 类的定义之前使用class Graph;


0
在编程中,需要在其中一个类之前预先声明该类。例如,在遍历头文件中,需要在遍历类之前添加以下语句:
class Graph;
这样,编译器就会知道在某个时刻会存在一个名为Graph的类。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接