错误:将const xxx作为xxx的this参数传递会丢弃限定符。

6

我正在将我的函数对象从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;
    }
};

由于Linux不支持_stricmp,而是使用strcasecmp,因此我将其更改为:
struct stringCompare{ 
    bool operator() (string lhs, string rhs){ // Returns true if lhs < rhs
        if(strcasecmp(lhs.c_str(), rhs.c_str())  < 0) return true;
        else return false;
    }
};

现在它正在抱怨"const"参数:

passing const stringCompare as this argument of bool stringCompare::operator()  
(std::string, std::string)â discards qualifiers

我不完全确定为什么它认为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;

可能与 const 限定符有关吗?警告是在 map 声明处还是其他地方报告的? - Kashyap
你最好使用可移植且操作std::string的字符串算法,而不是const char*。其中之一用于大小写不敏感比较。 - 111111
报告显示在此行:if(masterList->artistMap.count(songArtist) == 0)其中songArtist是一个字符串。 - Glem
@111111 我没有访问外部库(如boost)的权限,而STL也没有这样的比较函数。 - Glem
1个回答

10

两件事情:

  1. 将你的bool operator()定义为const。这是一个好习惯。这告诉编译器该函数不会对类的成员变量产生副作用。

  2. lhsrhs参数中添加const& 限定符。传递常量引用而不是复制内存是一个好习惯。通过将引用声明为const,您告诉编译器该函数不应对所引用的对象产生副作用。

您的operator()应如下所示:

bool operator() (const string &lhs, const string &rhs) const 
{
  return strcasecmp(lhs.c_str(), rhs.c_str())  < 0;
}

1
@Glem 不是 const bool operator()(...) 而是 bool operator()(...) const - Praetorian
我以为我已经尝试过这种方式了,但我想不是!这确实有效。为什么需要在参数后面加const?我以前没见过这样的写法。而且,如果没有任何内部函数是非常量的话,理论上它不应该担心const,对吧?只是为了让我能够在脑海中澄清错误发生的原因。谢谢! - Glem
@Glem const bool operator()(...) 的意思是函数的返回值是 const,而 bool operator()(...) 则表示函数本身是 const,即不对其类的成员变量产生副作用。 - George Skoptsov
@GeorgeSkoptsov 啊,这很有道理。谢谢你,George。 - Glem

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接