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 ;}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM