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

Wil*_*ris 6 c++ constructor

我收到错误:

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

由此:

#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
}
Run Code Online (Sandbox Code Playgroud)

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

K-b*_*llo 7

因为map需要DefaultConstructible值,因为当使用下标运算符并且未找到键时,它会将其映射到默认构造值.

  • @GManNickG:`operator []`需要_DefaultInsertable_,而不是整个地图.我认为这也是_C++ 03_中的情况...... (2认同)
  • ** - 1**"因为`map`需要*DefaultConstructible*values"从C++ 11及更高版本开始是不正确的. (2认同)

Luc*_*ore 3

mymap["hello"]可以尝试创建一个 value-initialized A,因此需要一个默认构造函数。

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