zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    零散
    修改element的内部样式的两种方式
    在vue-cli项目中使用第三方的js,不是es6格式
    Docker知识
    golang使用grpc
    vue中axios导出文件
    nginx、vue和thinkphp配置
    Mysql的一些问题
    数据库索引失效原因
    golang中使用grpc服务
  • 原文地址:https://www.cnblogs.com/savennist/p/12422022.html
Copyright © 2011-2022 走看看