2016-01-22 8 views
0

該代碼說明映射的插入,其中鍵類型是字符串,值是對類對象的引用。然而,有3重載函數,如超載=運算符,超載<運算符和重載==運算符..任何人都可以請解釋我爲什麼超載在這裏?STL - MAP - 將字符串作爲鍵和類對象添加爲值

#include <iostream> 
    #include <map> 
    using namespace std; 

    class AAA 
    { 
     friend ostream &operator<<(ostream &, const AAA &); 

     public: 
      int x; 
      int y; 
      float z; 

      AAA(); 
      AAA(const AAA &); 
      ~AAA(){}; 
      AAA &operator=(const AAA &rhs); 
      int operator==(const AAA &rhs) const; 
      int operator<(const AAA &rhs) const; 
    }; 

    AAA::AAA() // Constructor 
    { 
     x = 0; 
     y = 0; 
     z = 0; 
    } 

    AAA::AAA(const AAA &copyin) // Copy constructor to handle pass by value. 
    {        
     x = copyin.x; 
     y = copyin.y; 
     z = copyin.z; 
    } 

    ostream &operator<<(ostream &output, const AAA &aaa) 
    { 
     output << aaa.x << ' ' << aaa.y << ' ' << aaa.z << endl; 
     return output; 
    } 

    AAA& AAA::operator=(const AAA &rhs) 
    { 
     this->x = rhs.x; 
     this->y = rhs.y; 
     this->z = rhs.z; 
     return *this; 
    } 

    int AAA::operator==(const AAA &rhs) const 
    { 
     if(this->x != rhs.x) return 0; 
     if(this->y != rhs.y) return 0; 
     if(this->z != rhs.z) return 0; 
     return 1; 
    } 

    int AAA::operator<(const AAA &rhs) const 
    { 
     if(this->x == rhs.x && this->y == rhs.y && this->z < rhs.z) return 1; 
     if(this->x == rhs.x && this->y < rhs.y) return 1; 
     if(this->x < rhs.x) return 1; 
     return 0; 
    } 

    main() 
    { 
     map<string, AAA> M; 
     AAA Ablob ; 

     Ablob.x=7; 
     Ablob.y=2; 
     Ablob.z=4.2355; 
     M["A"] = Ablob; 

     Ablob.x=5; 
     M["B"] = Ablob; 

     Ablob.z=3.2355; 
     M["C"] = Ablob; 

     Ablob.x=3; 
     Ablob.y=7; 
     Ablob.z=7.2355; 
     M["D"] = Ablob; 

     for(map<string, AAA>::iterator ii=M.begin(); ii!=M.end(); ++ii) 
     { 
      cout << (*ii).first << ": " << (*ii).second << endl; 
     } 

     return 0; 
    } 

回答

0

它們不是重載,它們是操作符的定義。在這種特殊情況下,複製構造函數和賦值操作符將執行默認操作,因此應該省略它們。比較運算符應該返回bool而不是int,並且<比較可以更有效地編寫。在給出的代碼中都沒有使用比較,所以它們也是多餘的。如果AAA是地圖中的關鍵,那麼它們是必要的,但是因爲這是它們在那裏不需要的價值。

順便說一句,你可以循環定義爲

for (auto ii = M.begin(); ii != M.end(); ++i) 

,除非你的編譯器是足夠大,它不支持此使用auto

+0

follow @ 1201ProgramAlarm如果AAA將是關鍵,那麼<比較運算符將如何工作?可以用它來闡述它的工作嗎? –

相關問題