为什么在映射中存储时需要默认构造函数?

2021-12-30 00:00:00 constructor c++

我收到错误:

error: no matching function for call to 'A::A()'
note: candidates are: A::A(const A&)
note:                 A::A(const std::string&, size_t)

从这里:

#include <map>
#include <string>

using std::map;
using std::string;

class A {
public:
    string path;
    size_t size;
    A (const string& p, size_t s) : path(p), size(s) { }
    A (const A& f) : path(f.path), size(f.size) { }
    A& operator=(const A& rhs) {
        path = rhs.path;
        size = rhs.size;
        return *this;
    }
};

int main(int argc, char **argv)
{
    map<string, A> mymap;

    A a("world", 1);
    mymap["hello"] = a;      // <----- here
    A b(mymap["hello"]);     // <----- and here
}

请告诉我为什么代码需要一个没有参数的构造函数.

Please tell me why the code wants a constructor with no parameters.

推荐答案

mymap["hello"] 可以尝试创建一个值初始化的A,所以默认构造函数是必需的.

mymap["hello"] can attempt to create a value-initialized A, so a default constructor is required.

如果您使用类型 T 作为 map 值(并计划通过 operator[] 访问值),则需要默认构造 - 即您需要一个无参数(默认)构造函数.operator[] 如果没有找到提供键的值,映射上的 operator[] 将对映射值进行值初始化.

If you're using a type T as a map value (and plan to access value via operator[]), it needs to be default-constructible - i.e. you need a parameter-less (default) constructor. operator[] on a map will value-initialize the mapped value if a value with the key provided is not found.

相关文章