use*_*019 1 c++ oop return object
我正在尝试访问我的嵌套类,以便我可以返回此函数中的对象:
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;
}
Run Code Online (Sandbox Code Playgroud)
不用担心 for 循环(理论上它应该可以工作)我的主要问题是声明对象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
Run Code Online (Sandbox Code Playgroud)
我想访问
Graph.h:27: note: Graph::Edge::Edge(std::string, int)
Run Code Online (Sandbox Code Playgroud)
以下是我的 Graph 类的声明方式:(为了简单起见,我删除了函数和一些内容,使其更易于阅读)*
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....
};
Run Code Online (Sandbox Code Playgroud)
基本上,我需要知道的是在这个函数中声明 Edge 对象的正确方法。我真的很困惑,不知道除了 Graph::Edge v; 之外还能做什么
Graph::Edge
没有默认构造函数(不带参数的构造函数) - 它只有一个带 astring
和 an 的构造函数int
。您需要提供一个默认构造函数,如下所示:
Edge()
{
// ...
}
Run Code Online (Sandbox Code Playgroud)
或者在构造对象时传递 astring
和 an :int
Graph::Edge v("foo", 1);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4017 次 |
最近记录: |