繁体   English   中英

地图运算符[]的编译错误

[英]Compile error for map operator []

为什么会出现“ 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::operator []()之间存在差异:

std::map::at()仅返回对地图内部对象的引用。 如果没有给定键的对象,则会引发异常。

std::map::operator []()也确实返回引用,但是,如果没有给定键的对象,它将在映射内创建一个对象,并返回对该新创建对象的引用。 为了创建对象std::map必须调用默认构造函数(没有附加参数的构造函数)。

这就是您的代码无法编译的原因:您的类MyRec不是默认可构造的,但是std::map::operator []需要此代码。


因此,您有三个选择:

  1. 使用std::map::insert()
  2. 使用std::map::emplace()
  3. 使MyRec默认可构造。

在您的代码中,您提到希望[] operator的工作方式与以下相同:

    (*((recMap.insert(std::make_pair(key,rec))).first)).second;

但这和那句话一样。 而是和:

    (*((recMap.insert(std::make_pair(key,MyRec()))).first)).second;

如此编写,希望可以更容易地了解为什么代码无法编译(即MyRec没有定义无参数的构造函数 )。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM