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

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

问题描述

我收到错误:

 错误:没有匹配的函数调用'A :: A 
注意:候选是:A :: A(const A&)
注意:A :: A(const std :: string& size_t)
/ pre>

从这里:

  #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 ){}
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
}

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

解决方案

mymap [hello] 可以尝试创建一个值

如果您使用的是<$ c $

作为映射值(并计划通过运算符[]访问值 ),它需要默认可构造 - 即您需要一个无参数(默认)构造函数在地图上的运算符[] 将在未找到具有提供的键的值时初始化映射的值。


I'm getting the error:

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

From this:

#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"] can attempt to create a value-initialized A, so a default constructor is required.

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天全站免登陆