Dev 中编程出现的一个小错误-记住就好

C++ STL编译报错:error: error passing 'const' as 'this' argument

用C++ STL(标准模板库)编写仿函数的时候,编译报错:
error: passing 'const FindNameOrAddress' as 'this' argument of 'bool FindNameOrAddress::operator()(std::string, std::string)' discards qualifiers [-fpermissive]
其中:FindNameOrAddress 为类名。在使用STL中的某些算法的时,有时候出于需要,不得不自己去实现函数对象,然后再用适配器来绑定并匹配函数参数问题。

 1 //函数适配器 bind1st  bind2nd ,二元函数对象需要继承binary_function<参数类型,参数类型,返回值类型>;
 2 //若为一元函数对象,则需继承unary_function
 3 struct FindNameOrAddress : public std::binary_function<std::string,std::string, bool>
 4 {
 5     bool operator()(const std::string stuA,const std::string stuB)
 6     {
 7         return strncmp(stuA.c_str(),stuB.c_str(),stuA.length())?true:false;
 8         //可以直接 return  stuA>stuB?true:false;
 9     }
10 };

上面的类编译就会报错,因为我们在进行括号"()"重载时候,应该将其声明为“const 属性。正确的形式如下:

1 //函数适配器 bind1st  bind2nd ,二元函数对象需要继承binary_function<参数类型,参数类型,返回值类型>;
2 //若为一元函数对象,则需继承unary_function
3 struct FindNameOrAddress : public std::binary_function<std::string,std::string, bool>
4 {
5     bool operator()(const std::string stuA,const std::string stuB) const
6     {
7         return strncmp(stuA.c_str(),stuB.c_str(),stuA.length())?true:false;
8     }
9 };

综上所述:加个const就好

OK

猜你喜欢

转载自www.cnblogs.com/savennist/p/12422022.html
Dev