由于构造函数,无法推回 class 对象

Can't push back a class object because of constructor

我有这段代码,我试图将一个已经构建的元素从 unordered_map:

推入一个向量
class A {
public:
    A(const std::string& a) {}
}

int main() {
    std::unordered_map<std::string, A> map {{"A", A("A")}, {"B", A("B")}};
    std::vector<A> vec;
    vec.push_back(map["A"]);
}

但是为什么我收到有关矢量的错误 push_back:

/usr/local/include/c++/6.3.0/tuple:1586:70: error: no matching function for call to 'A::A()'
         second(std::forward<_Args2>(std::get<_Indexes2>(__tuple2))...)
                                                                      ^
main.cpp:8:9: note: candidate: A::A(const string&)
         A(const std::string& a) {}
         ^
main.cpp:8:9: note:   candidate expects 1 argument, 0 provided
main.cpp:6:7: note: candidate: constexpr A::A(const A&)
 class A {
       ^
main.cpp:6:7: note:   candidate expects 1 argument, 0 provided
main.cpp:6:7: note: candidate: constexpr A::A(A&&)
main.cpp:6:7: note:   candidate expects 1 argument, 0 provided

std::map::operator[]requires the mapped type (in your case, A) to be default-insertable,所以你必须提供一个默认的构造函数,你没有,例如:

class A {
public:
    A(){}
    A(const std::string& a) {}
}

问题是,当使用 std::unordered_map::operator[] (ref) your mapped_type (A) must be default constructible, the key_type must be move constructible 时,您的示例中的 std::string 不是问题。

#include <iostream>
#include <vector>
#include <string>
#include <unordered_map>

class A {
public:
    A(const std::string& a) {}
    A() {} // Default constructor
};

int main() {
    std::unordered_map<std::string, A> map {{"A", A("A")}, {"B", A("B")}};
    std::vector<A> vec;
    vec.push_back(map["A"]); // Requires default constructor
    vec.push_back(map.at("A")); // Do NOT requires default constructor
}

对于带有 C++11 标记的问题,上述答案可能会提到您不需要默认构造函数的实际实现,但您可以使用 =default 说明符来传达这一点是需要它的唯一原因。

class A {
public:
    A() = default;
    A(const std::string& a) {}
}