zoukankan      html  css  js  c++  java
  • passing ‘const ’ as ‘this’ argument of ‘’ discards qualifiers 错误处理

    示例程序:

    #include <iostream> 

    #include <set>   

    using   namespace std ;   

    class   StudentT  

    {   

    public :      

      int id ; string name ;  

    public :      

      StudentT ( int _id , string _name )   : id ( _id ), name ( _name )   {       }      

      int getId ()   {           return id ;       }

      string getName ()   {           return name ;       }  

    };   

    inline   bool   operator <   ( StudentT s1 ,   StudentT s2 )   {       return s1 . getId ()   < s2 . getId ();   }   

    int main ()  

    {       

      set < StudentT > st ;      

      StudentT s1 ( 0 ,   "Tom" );      

      StudentT s2 ( 1 ,   "Tim" );

      st . insert ( s1 ); st . insert ( s2 );      

      set < StudentT >   ::   iterator itr ;      

      for   ( itr = st . begin (); itr != st . end (); itr ++)  

      {

        cout << itr -> getId ()   <<   " "   << itr -> getName ()   << endl ;      

      }      

      return   0 ;  

    }

    错误提示:

      ../main.cpp:35: error: passing 'const StudentT' as 'this' argument of 'int StudentT::getId()' discards qualifiers

      ../main.cpp:35: error: passing 'const StudentT' as 'this' argument of 'std::string StudentT::getName()' discards qualifiers

    原因:

      std::set的对象存储const StudentT 。 所以当您尝试调用getId() const对象的编译器检测到一个问题,即你调用一个const对象的非const成员函数这是不允许的,因为非const成员函数不作任何承诺,不修改对象,所以编译器将会使一个安全的假设getId()可能试图修改的对象,但同时,它也注意到,该对象是const,所以任何试图修改const对象应该是一个错误。 因此,编译器会生成错误消息。 

    解决方法:

      解决方法很简单:函数的const:  

      int  getId ()   const   {       return  id ;   }

      string getName ()   const   {       return  name ;}

  • 相关阅读:
    轻松搭建基于 SpringBoot + Vue 的 Web 商城应用
    Serverless 实战 —— Funcraft + OSS + ROS 进行 CI/CD
    急速搭建 Serverless AI 应用:为你写诗
    O'Reilly 1500 份问卷调研:2019 年 Serverless 落地到底香不香?
    2019 阿里巴巴云原生这一年
    快速部署 Spring PetClinic 到函数计算平台
    1354. Construct Target Array With Multiple Sums
    1352. Product of the Last K Numbers
    1351. Count Negative Numbers in a Sorted Matrix
    1347. Minimum Number of Steps to Make Two Strings Anagram
  • 原文地址:https://www.cnblogs.com/yunsicai/p/3387676.html
Copyright © 2011-2022 走看看