将全局常量作为"this"参数传递会丢弃限定符

Passing global constant as 'this' argument discards qualifiers

本文关键字:this 常量 全局 参数传递      更新时间:2023-10-16

在我的程序中,我有一个全局const std::map变量和一个试图读取其内容的函数。编译器(G++5.2.0 C++0x)然后给我一个错误passing ‘const std::map<const char*, const char>’ as ‘this’ argument discards qualifiers [-fpermissive]。我不能为函数指定cv限定符,因为它不是成员函数。我该怎么办?

代码如下:

const map <const char*, const char> opcodes = 
{
    {"ABCDE", 123},
};
bool _cmdmatch (const char* cmd, const char* cmdlist[], char count)
{
    ...
        if (opcodes[cmd] == opcodes[cmdlist[i]]) return true;
        //if (opcodes.at(cmd) == opcodes.at(cmdlist[i])) return true; //The solution
    ...
}

我假设您正在使用operator[]从映射中读取,这在const映射上是无法使用的。应该使用at()获取具有特定键的元素,或者使用find()搜索元素。两者都有const版本,可以在const映射上使用。