2013-12-22 146 views
0

我试图访问我的嵌套类,所以我可以在这个函数返回的对象:如何创建嵌套类的对象?

Graph::Edge Graph::get_adj(int i) 
{ 
    Graph::Edge v; 
    int count = 0; 
    for(list<Edge>::iterator iterator = adjList[i].begin(); count <= i ;++iterator) 
    { 
     v.m_vertex = iterator->m_vertex; 
     v.m_weight = iterator->m_weight; 
    } 
    return v; 
} 

不要担心for循环(它应该theoreticly工作)我的主要问题是与申报对象Graph::Edge v;它不工作!这是错误我得到:

$ make -f makefile.txt 
g++ -Wall -W -pedantic -g -c Graph.cpp 
Graph.cpp: In member function `Graph::Edge Graph::get_adj(int)': 
Graph.cpp:124: error: no matching function for call to `Graph::Edge::Edge()' 
Graph.cpp:43: note: candidates are: Graph::Edge::Edge(const Graph::Edge&) 
Graph.h:27: note:     Graph::Edge::Edge(std::string, int) 
makefile.txt:9: recipe for target `Graph.o' failed 
make: *** [Graph.o] Error 1 

我要访问的

Graph.h:27: note:     Graph::Edge::Edge(std::string, int) 

下面是我的类图中声明:(我拿出的功能和一些东西简单,并使其更易于阅读) *

class Graph 
{ 
private: 
    vector< list<Edge> > adjList; 
public: 
    Graph(); 
    ~Graph(); 
    class Edge 
    { 
    public: 
     Edge(string vertex, int weight) 
     { 
      m_vertex = vertex; 
      m_weight = weight; 
     } 
     ~Edge(){} 
     string m_vertex; 
     int m_weight; 
    }; 

    vector < list <Edge> > get_adjList(){return adjList;} 
    //Other functions.... 

}; 

基本上,所有我需要知道的是申报边缘的物体在此功能的正确方法。我真的很困惑,不知道除了Graph :: Edge v以外还有什么可以做的事情;

+0

我不理解'get_adj(i)'的含义,是否应该返回顶点“i”的邻接列表的全部或邻居列表中的某个未指定*顶点的邻接列表的第i个邻接项?我假设你的'adjList'是一个每个顶点邻接列表的acutally,这意味着'adjList [i]'包含顶点'i'的邻接点。 – leemes

回答

4

Graph::Edge没有默认构造函数(不带参数的构造函数) - 它只有一个构造函数,它需要stringint。要么你需要给一个默认的构造函数,像这样:

Edge() 
{ 
    // ... 
} 

,或通过string和构造对象时int

Graph::Edge v("foo", 1); 
3

你的问题是,你声明中的边缘构造类(Edge(string vertex, int weight)),因此你没有默认的构造函数。当您尝试创建边缘类的实例(您使用Graph::Edge v)时,它会尝试调用此默认构造函数。

您需要明确声明Edge()默认构造函数或使用您创建的构造函数声明变量。