首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

error 2678 no operator found with take a left-hand operand,该如何处理

2013-09-28 
error 2678no operator found with take a left-hand operand#include map#include stringusing names

error 2678 no operator found with take a left-hand operand

#include <map>
#include <string>
using namespace std;

struct any {
any() {}
any(int x) {}
};
struct record : map<string, any> {
};
int main() {

record r;
r["aa"] = 123;
const any& a = r["aa"]; // ok

const record& cr = r;
const any& a = cr["aa"]; // error 2678
}

最后一行用到 const 引用,就会出2678错误,请问如何能解决const & 问题。
[解决办法]
这样

    const record& cr = r;
    auto const iter = cr.find("aa");
    if (cr.end() != iter)
    {
     const any& a = iter->second;
    }

map::operator[] 在没有的情况下会自动添加,所以无法与 const 对象连用。

热点排行