You need to enable JavaScript to run this app. C++类const成员函数调用unordered_map.insert无重载实例错误如何解决
优惠活动
大模型
产品
解决方案
定价
更多

C++类const成员函数调用unordered_map.insert无重载实例错误如何解决

问题原因

你代码的核心问题出在reassemblestream函数的const修饰符上:

  • 成员函数末尾加const修饰,代表该函数是只读成员函数,内部不允许修改类的任意非mutable成员变量
  • 你在函数内调用word_count.insert是要修改unordered_map的内容,违反了const函数的约束,因此编译器抛出匹配错误
  • 你看到的错误完整翻译为:

E1087 不存在可匹配的重载函数std::unordered_map<_Kty, _Ty,_Hasher, _Keyeq, _Alloc>::insert [其中模板参数分别为:_Kty=size_t, _Ty=std::string, _Hasher=std::hash<size_t>, _Keyeq=std::equal_to<size_t>, _Alloc=std::allocator<std::pair<const size_t, std::string>>] 实例,当前对象附带的类型限定符阻止了函数匹配。

解决方案

两种方案按需选择即可:

方案1:移除函数的const修饰(更常用,符合常规逻辑)

如果该函数本身就是要修改类成员状态,直接去掉const修饰符即可:

  1. 修改stream.h中的函数声明:
// 去掉末尾的const
void reassemblestream();
  1. 同步修改stream.cpp中的函数实现:
void stream::reassemblestream()
{
    static  size_t a = 1;
    string fe = "dfi";
    word_count.insert({ 1,"dfs" });
    word_count.insert(make_pair(a, fe));
}

方案2:给成员变量加mutable修饰(仅特殊场景使用)

如果有明确需求必须保留该函数的const属性(例如需要在const修饰的stream对象上调用该函数),可以给word_count加上mutable修饰,允许它在const函数中被修改:

class stream
{
private:
    // 加mutable修饰
    mutable std::unordered_map<size_t, std::string> word_count;
public:
    void reassemblestream() const;
};

内容的提问来源于stack exchange,提问作者Jam。

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.08 08:15:01