【问题标题】:'No matching function for call' error when inserting class into a STL map将类插入 STL 映射时出现“调用没有匹配函数”错误
【发布时间】:2012-11-08 16:10:24
【问题描述】:

我在 C++ 中有一个 STL 映射,其中键是一个无符号整数,值是一个类,其构造函数是:

Foo::Foo(unsigned int integerValue){
    //Some stuff
}

在其他课程中,我在标题处声明了 std::map:

private:
    std::map<unsigned int, Foo> *m_mapFoo;

在 cpp 文件中,我创建了它并插入了 Foo 的实例:

m_mapFoo = new std::map<unsigned int, Foo>;
m_mapFoo->insert(0, new Foo(0));
m_mapFoo->insert(1, new Foo(1));

但我在插入方法中遇到以下错误:

no matching function for call to ‘std::map<unsigned int, Foo, std::less<unsigned int>, std::allocator<std::pair<const unsigned int, Foo> > >::insert(const unsigned int&, Foo*)’

find 方法的类似问题:

m_mapFoo.find(0)->second->someFunctionIntoFooClass();

错误的地方如下:

request for member ‘find’ in ‘((Foo*)this)->Foo::m_mapGeoDataProcess’, which is of non-class type ‘std::map<unsigned int, Foo, std::less<unsigned int>, std::allocator<std::pair<const unsigned int, Foo> > >*’

附加说明:我没有 Foo 复制构造函数,但我认为这不是问题。

对理解这个错误有帮助吗?

【问题讨论】:

  • 如果您没有复制构造函数,您希望如何复制到地图中?
  • 我已经阅读了stackoverflow,有些人说你必须有,有些人说你不需要。但我不知道这是否仅适用于 [] 插入而不适用于插入方法。见stackoverflow.com/questions/1478330/…
  • 您需要insert 的复制构造函数。不过emplace 不需要它。
  • @Pubby OP 可能有编译器合成的复制构造函数。

标签: c++ dictionary stl std


【解决方案1】:

从您提供的少量信息来看,您似乎不太可能需要在任何地方使用指针:试试这个:

在标题中:

private:
    std::map<unsigned int, Foo> m_mapFoo;

在 cpp 文件中:

m_mapFoo[0] = Foo(0);
m_mapFoo[1] = Foo(1);

operator[] 的语义与.insert() 略有不同。如果您需要.insert(),请使用它。但除非您依赖细微差别,否则请使用更易读的operator[]

与 find 方法类似,如果您避免使用指针并使用 operator[],则表达式变得更具可读性:

m_mapFoo[0].someFunctionIntoFooClass();

【讨论】:

    【解决方案2】:

    您有一个指向包含 Foo 值的映射的指针

    std::map<unsigned int, Foo> *m_mapFoo;
    

    您将其视为包含Foo 指针值:

    std::map<unsigned int, Foo*> *m_mapFoo;
    

    试试这个:

    m_mapFoo = new std::map<unsigned int, Foo>;
    m_mapFoo->insert(std::make_pair(0, Foo(0)));
    m_mapFoo->insert(std::make_pair(1, Foo(1)));
    

    至于第二个错误,你有一个指向地图的指针,所以你需要

    std::map<unsigned int, Foo>::iterator it = m_mapFoo->find(0);
    if (it) {
      it->second.someFunctionIntoFooClass();
    } else {
      // entry not found
    }
    

    【讨论】:

    • 这似乎可行,谢谢!但是在 find 方法中仍然存在第二个错误。有什么想法吗?
    • @RomanRdgz 我添加了一些关于第二个错误的内容。请注意,您应该检查std::map::find 的结果。
    • 错误仍然存​​在,相同:请求成员查找...我还包括 具有相同的结果(我忘记了)
    • @RomanRdgz 抱歉,我在使用std::map::find 并调用Foo 函数的行中打错了。它现在应该可以工作了。
    【解决方案3】:

    您的地图被键入以存储Foo 类型的对象,而不是指向Foo 类型的对象的指针。当您尝试使用 new 初始化元素并通过 -&gt; 访问其成员时,您可能想要:

    private:
        std::map<unsigned int, Foo*> *m_mapFoo;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-19
      • 2013-05-05
      • 2013-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-23
      相关资源
      最近更新 更多