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