C++ 错误:将常量xxx作为xxx的此参数传递将丢弃限定符

C++ 错误:将常量xxx作为xxx的此参数传递将丢弃限定符,c++,parameters,compiler-errors,constants,functor,C++,Parameters,Compiler Errors,Constants,Functor,我在将我的functor从windows移植到linux时遇到问题。(传递给stl::map的函子,用于严格弱排序) 原件如下: struct stringCompare{ // Utilized as a functor for stl::map parameter for strings bool operator() (string lhs, string rhs){ // Returns true if lhs < rhs if(_stricmp(lhs.

我在将我的functor从windows移植到linux时遇到问题。(传递给stl::map的函子,用于严格弱排序) 原件如下:

struct stringCompare{ // Utilized as a functor for stl::map parameter for strings 
    bool operator() (string lhs, string rhs){ // Returns true if lhs < rhs
        if(_stricmp(lhs.c_str(), rhs.c_str())  < 0) return true;
        else return false;
    }
};
bool operator() (const string &lhs, const string &rhs) const 
{
  return strcasecmp(lhs.c_str(), rhs.c_str())  < 0;
}
我不完全确定为什么它假设stringCompare应该是一个常数

它对这个被实例化感到愤怒的一行是:

if(masterList->artistMap.count(songArtist) == 0) 
artistMap是带有字符串键的stl::map

我不确定我错在哪里。我试图将bool operator()参数更改为const,因为它似乎在抱怨某种非常量参数传递。这不起作用,将'bool operator()'更改为'const bool operator()'也不起作用

据我所知,strcasecmp是一个const函数,所以不管我传递的是非常量参数还是常量参数(c_str()也是const),我都不确定哪里出错了

我在谷歌上搜索过类似的问题,但从我在stackoverflow和其他几个地方看到的情况来看,我仍然不能完全理解这个问题

我使用的数据类型是:

map<string, set<song, setSongCompare>*,stringCompare > artistMap;
地图艺术地图;
两件事:

  • bool操作符()定义为
    const
    。这只是一个很好的练习。这告诉编译器该函数不会对类的成员变量产生副作用

  • lhs
    rhs
    参数中添加
    const&
    限定符。传递常量引用而不是到处复制内存也是一种很好的做法。通过将引用声明为
    const
    ,您告诉编译器此函数不应对引用的对象产生副作用

  • 您的
    操作符()
    应如下所示:

    struct stringCompare{ // Utilized as a functor for stl::map parameter for strings 
        bool operator() (string lhs, string rhs){ // Returns true if lhs < rhs
            if(_stricmp(lhs.c_str(), rhs.c_str())  < 0) return true;
            else return false;
        }
    };
    
    bool operator() (const string &lhs, const string &rhs) const 
    {
      return strcasecmp(lhs.c_str(), rhs.c_str())  < 0;
    }
    
    bool操作符()(常量字符串和lhs、常量字符串和rhs)常量
    {
    返回strcasecmp(lhs.c_str(),rhs.c_str())<0;
    }
    
    可能与
    const
    限定符有关??警告是在
    map
    声明或其他地方报告的吗?最好使用可移植的字符串算法,并在std::string而不是const char*上操作。有一个用于不区分大小写的比较。它在这一行报告:if(masterList->artistMap.count(songArtist)==0),其中songArtist是一个string@111111我没有访问boost等外部库的权限,stl也没有这种比较函数@Glem Not
    const bool operator()的可能副本(…)
    但是
    bool operator()(…)const
    我以为我已经尝试过这样做了,但我想不会!这确实奏效了。为什么参数后需要常量?我以前没见过这个。另外,如果没有一个内部函数是非常数的,理论上它不应该担心常数吗?这样我就可以在头脑中澄清错误发生的原因。谢谢大家!@Glem
    const bool operator()(…)
    表示函数的返回为
    const
    ,而
    bool operator()(…)
    表示函数本身为
    const
    ,即对其类的成员变量没有副作用。@GeorgeSkoptsov啊,这是有道理的。谢谢你,乔治。