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中的某些算法的时,有时候出于需要,不得不自己去实现函数对象,然后再用适配器来绑定并匹配函数参数问题。

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

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

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

猜你喜欢

转载自blog.csdn.net/lixiaogang_theanswer/article/details/80920872
今日推荐