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

在使用C++ STL编写仿函数时遇到编译错误,问题出在FindNameOrAddress类中。错误提示表明在调用'const'对象的成员函数时传错了参数。解决办法是在定义成员函数时添加'const'修饰,确保函数可以被'const'对象正确调用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

用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;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

内核之道

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值