为什么我会收到“recMap[key] = rec;”的编译错误在下面的代码中,但等效的语句工作正常吗?我有其他代码可以执行此操作。我错过了什么简单的事情?
#include <map>
class MyRec {
public:
MyRec(int numberIn) : myNumber(numberIn) { };
int myNumber;
};
int main(int argc, char **argv)
{
typedef std::map<int, MyRec> Recs;
Recs recMap;
int num=104702;
int key=100923;
MyRec rec(num);
recMap[key] = rec; // Doesn't compile
// error: no matching function for call to MyRec::MyRec()
// samp.cpp:5: note: candidates are: MyRec::MyRec(int)
// samp.cpp:3: note: MyRec::MyRec(const MyRec&)
// Why do I receive the compile error for the above if it is the same as:
(*((recMap.insert(std::make_pair(key,rec))).first)).second;
recMap.insert(std::pair<int, MyRec>(key,rec)); // Works also of course
}
最佳答案
考虑这个片段:
std::map<int, Foo> map;
map[0];
即使没有为键 0 插入对象,这实际上也可以正常工作。原因是,std::map::at()
和 std 之间存在差异: :map::运算符 []()
:
std::map::at()
仅返回对 map 内对象的引用。如果给定键不存在对象,则会引发异常。
std::map::operator []()
也返回一个引用,但是如果给定键没有对象,它会在映射并返回对此新创建的对象的引用。为了创建对象 std::map
必须调用默认构造函数(没有附加参数的构造函数)。
这就是您的代码无法编译的原因:您的类 MyRec
不是默认可构造的,但 std::map::operator []
需要这个。
因此您有三个选择:
- 使用
std::map::insert()
- 使用
std::map::emplace()
- 使
MyRec
默认可构造。
关于c++ - 映射运算符 [] 的编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22561405/