我有一个类:class1
使用私有(private)成员变量:
std::unordered_map<std::string, class2> s_list;
我正在尝试插入或分配 class2
的对象在上面s_list
.
class2
具有以下形式的复制构造函数:
class2::class2(const class2& obj)
{
x = obj.x;
y = obj.y;
}
它还有另一个构造函数:
class2::class2(std::string x1, double y1)
{
x = x1;
y = y1;
}
在 class1
的函数之一中,我有以下几行:
class2 s_obj(x1, y1);
s_list[x1] = s_obj;
但是,它会抛出错误:
error: no matching function for call to ‘class2::class2()’
second(std::forward<_Args2>(std::get<_Indexes2>(__tuple2))...)
^
我在这里错过了什么?
最佳答案
您缺少默认的 ctor
。在 unordered_map
中,如果没有匹配 key
的值,它会创建一个默认值并返回对它的引用。
考虑下标运算符 []
。 See Here .仔细观察返回的T&
如果您执行 s_list["foo"]
并且没有与“foo”关联的 value
,它会在 unordered_map 中创建一个条目,其中包含 key
"foo"并通过调用其默认构造函数返回对默认值的引用。
在你的 class2 中你没有。要修复它,请创建一个默认构造函数
class class2 // horrible name btw
{
class2() = default;
}
或使用插入
。 Reference
关于c++ - 在 unordered_map 中分配或插入类对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49156149/