为什么在映射中存储时需要默认构造函数? [英] Why is a default constructor required when storing in a map?

查看:23
本文介绍了为什么在映射中存储时需要默认构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到错误:

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.

这篇关于为什么在映射中存储时需要默认构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆