[英]Compile error for map operator []
Why do I get a compile error for "recMap[key] = rec;" 为什么会出现“ recMap [key] = rec;”的编译错误? in the below code but the equivalent statements work fine? 在下面的代码中,但等效的语句工作正常吗? I have other code that does this. 我还有其他代码可以做到这一点。 What simple thing am I missing? 我缺少什么简单的东西?
#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
}
Consider this snippet: 请考虑以下代码段:
std::map<int, Foo> map;
map[0];
This will actually work fine even if havent inserted an object for key 0. The reason is, that there is a difference between std::map::at()
and std::map::operator []()
: 即使没有为键0插入对象,这实际上也可以正常工作。原因是std::map::at()
和std::map::operator []()
之间存在差异:
std::map::at()
only returns a reference to an object inside the map. std::map::at()
仅返回对地图内部对象的引用。 If there isnt an object for the given key, an exception is thrown. 如果没有给定键的对象,则会引发异常。
std::map::operator []()
does also return a reference, however if there no object for the given key, it creates an object inside the map and returns a reference to this newly created object. std::map::operator []()
也确实返回引用,但是,如果没有给定键的对象,它将在映射内创建一个对象,并返回对该新创建对象的引用。 In order to create the object std::map
must call the default constructor (a constructor with no additional arguments). 为了创建对象std::map
必须调用默认构造函数(没有附加参数的构造函数)。
That is the reason why you code wont compile: Your class MyRec
is not default constructable, but std::map::operator []
requires this. 这就是您的代码无法编译的原因:您的类MyRec
不是默认可构造的,但是std::map::operator []
需要此代码。
Thus you have three options: 因此,您有三个选择:
std::map::insert()
使用std::map::insert()
std::map::emplace()
使用std::map::emplace()
MyRec
default constructable. 使MyRec
默认可构造。 In your code, you mention that you expect the [] operator
to work the same as: 在您的代码中,您提到希望[] operator
的工作方式与以下相同:
(*((recMap.insert(std::make_pair(key,rec))).first)).second;
But it is not the same as that statement; 但这和那句话不一样。 rather it's the same as: 而是和:
(*((recMap.insert(std::make_pair(key,MyRec()))).first)).second;
Written like this, hopefully it's easier to see why the code doesn't compile (that is, MyRec does not define a parameter-less constructor ). 如此编写,希望可以更容易地了解为什么代码无法编译(即MyRec没有定义无参数的构造函数 )。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.