我的程序有问题。我在C ++中创建了一个Graph类,现在我想在拓扑上对它进行排序。问题是,我的拓扑排序接受任何DirectedGraph,但是当我想给它一个孩子(例如AdjacencyListDirectedUnweightedGraph)时,它拒绝转换。这是我的.hpps:
TopoSort.hpp:
#ifndef TOPOSORT_HPP
#define TOPOSORT_HPP
#include "../Graph.hpp"
#include "../DirectedGraph/AdjListUWDG.hpp"
#include "../DirectedGraph/DirectedGraph.hpp"
#include "../UnDirectedGraph/AdjListWUDG.hpp"
class TopoSort
{
protected:
std::vector<int> _sortedList;
std::vector<int> _KahnTopNodes;
public:
TopoSort();
~TopoSort();
void KahnSort(DirectedGraph &list);
void KahnSortTopNodes(DirectedGraph &list);
};
#endif
DirectedGraph.hpp
#ifndef DIRECTEDGRAPH_HPP
#define DIRECTEDGRAPH_HPP
#include <iostream>
#include <string>
#include <vector>
#include "../Graph.hpp"
class DirectedGraph
: public Graph
{
protected:
std::vector<int> _inDegree;
std::vector<int> _outDegree;
public:
DirectedGraph(){};
virtual ~DirectedGraph(){};
int inDegree(int a){return (_inDegree[a]);}
int outDegree(int a){return (_outDegree[a]);}
bool rangeCheck(int a, int b)
{
if (a >= _vertices || b >= _vertices || a == b)
{
std::cout << "The edge " << a << " - " << b << " is invalid." << std::endl;
return (false);
}
return (true);
}
};
#endif
AdjListDG.hpp
#ifndef ADJListDG_HPP
#define ADJListDG_HPP
#include <string>
#include <vector>
#include "DirectedGraph.hpp"
class AdjListDG
: public virtual DirectedGraph
{
protected:
std::vector<std::vector<std::pair<int, int> > > _adjList;
public:
virtual ~AdjListDG();
bool existsEdge(Edge);
bool existsEdge(int, int);
void putEdge(Edge);
void removeEdge(Edge);
int adjacentVertices(int);
bool areAdjacent(int, int);
};
#endif
AdjListUWDG.hpp
#ifndef AdjListUWDG_HPP
#define AdjListUWDG_HPP
#include <string>
#include <vector>
#include "AdjListDG.hpp"
class AdjListUWDG
: public virtual AdjListDG
{
public:
AdjListUWDG(std::string);
virtual ~AdjListUWDG();
};
#endif
而且,我的主要。
#include <iostream>
#include <string>
#include <fstream>
#include "UnDirectedGraph/AdjListWUDG.hpp"
#include "UnDirectedGraph/AdjListUWUDG.hpp"
#include "UnDirectedGraph/AdjMatWUDG.hpp"
#include "UnDirectedGraph/AdjMatUWUDG.hpp"
#include "Assgn3/TopoSort.hpp"
int main(int argc, char** argv)
{
if (argc != 2)
{
std::cout << "Usage : ./graph FILENAME" << std::endl;
return(0);
}
std::string filename = argv[1];
AdjListWUDG gr(filename);
TopoSort tsort;
std::ofstream fichier("results.txt", std::ios::out | std::ios::trunc);
if(fichier)
{
if (gr.existsEdge(1, 2))
fichier << "1 - 2 exist" << std::endl;
fichier << "numedge == " << gr.numEdges() << std::endl;
fichier << "adjver 1 == " << gr.adjacentVertices(1) << std::endl;
fichier << "adj 1 2 == " << gr.areAdjacent(1,2) << std::endl;
fichier << "adj 1 0 == " << gr.areAdjacent(1,0) << std::endl;
fichier << "adj 0 2 == " << gr.areAdjacent(0,2) << std::endl;
}
DirectedGraph * gr2 = &gr;
tsort.KahnSort(*gr2);
}
就是这样!我很抱歉,如果它看起来很明显或什么的,我只是看不出有什么问题。还试过动态和静态演员,没有成功。提前谢谢!
编辑:
我是傻瓜。试图投射参考,而不是对象本身......static_cast而不是static_cast
抱歉这个无用的帖子!
答案 0 :(得分:0)
转换为引用而不是对象本身,这是愚蠢的,对不起!