noɥ*_*ɐɹƆ 4 c++ constructor compiler-errors
我收到以下错误
In file included from /Users/james/ClionProjects/United States Computing Olympiad/graphs.cpp:2:
In file included from /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/string:439:
In file included from /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/algorithm:628:
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/memory:1673:31: error: no matching constructor for initialization of 'Vertex'
::new((void*)__p) _Up(_VSTD::forward<_Args>(__args)...);
Run Code Online (Sandbox Code Playgroud)
这是我的代码的相关部分的删节版本:
class Vertex {
public:
int label;
vector<Vertex> adjacent_vertices;
Vertex(const int l) : label(l) { }
Vertex(const int l, vector<Vertex> adjacents) : label(l), adjacent_vertices(adjacents) { }
Vertex(const Vertex& other_vertex) : label(other_vertex.label), adjacent_vertices(other_vertex.adjacent_vertices){ }
};
class Graph {
public:
unordered_map<int, Vertex> vertices;
protected:
Vertex getmake_vertex(const int v) {
if (vertices.find(v) == vertices.end() ) {
// not found, make new vertex
vertices[v] = Vertex(v);
}
return vertices[v];
};
};
Run Code Online (Sandbox Code Playgroud)
我已经确认,在其他所有注释掉的情况下运行它会产生编译器错误.有人可以向我解释为什么会发生这种情况以及如何解决这个问题?这是一个完整的编译器输出的要点.
当你说它vertices[v] = Vertex(v);必须Vertex为键创建一个v(在赋值之前),但Vertex没有默认的构造函数.
你应该使用vertices.insert(make_pair(v, Vertex(v)))甚至是什么vertices.emplace(v, Vertex(v))
这也适用于return vertices[v];.即使你和我知道在返回此返回语句时v已经存在值,但编译器不会并且仍然必须生成可能产生一个的代码,这会导致错误.
设置它将return vertices.find(v)->second;修复该部分.没有必要检查并确保find价值不是end因为我们只是把它放入,如果不存在的话.