2017-08-14 70 views
0

我有這個類在C++:如何創建operator []進行設置?

class Company{ 
    string PhoneNumber; 
    std::set<ER*> Rooms; 
public: 
    // some other functions 
} 

現在我想要寫操作=這一類,我有一個問題要經過一套

這是我走到這一步:

Company& Company::operator=(const Company& company){ 
    if(this==&company){ 
     return *this; 
    } 
    int numRooms=Rooms.size(); 
     for(int i=0;i<numRooms;i++){ 
      delete Rooms[i]; 
     } 
    int numCompanyRooms=company.Rooms.size(); 
     for(int i=0;i<numCompanyRooms;i++){ 
     Rooms[i]= new ER(*company.Rooms[i]); // i get error no match operator [] ! 
       } 
     Rooms=company.Rooms; 
     return *this; 
} 

任何幫助我在做什麼錯在這裏!?

+2

拋開不存在的'operator []',你需要向你的[橡皮鴨]解釋你的代碼(https://en.wikipedia.org/wiki/Rubber_duck_debugging)。 – juanchopanza

+0

你確定'std :: set'已經重載'operator []'? –

+1

無關,但我確定希望兩組的大小都是一樣的...... – donkopotamus

回答

0

您不能按索引訪問set中的元素。您必須遍歷整個set。 要清空現有的一套,你需要明確delete元素,然後調用clear。然後從company複製Rooms,你將不得不遍歷Company.Rooms。還有,你必須找出如何打算使ER副本,因爲它取決於定義爲ER

Company& Company::operator=(const Company& company) 
{ 
    if(this==&company) 
     return *this; 
    for(auto itr = Rooms.begin(); itr!=Rooms.end(); itr++) 
    { 
     ER* deleteMe = *itr; 
     delete deleteMe; 
    } 
    Rooms.clear();//Empty the set.Note that clear() does not delete so we explicitly called it before. 
    for(auto itr = company.Romms.begin(); itr!=company.Rooms.end(); itr++) 
    { 
     ER* newER = new ER(); 
     //copy *itr into newER in proper way.This depends on 
     //definition of ER.Maybe you can check if there assignment operator 
     //for ER as well and utilize it. 
     Rooms.insert(newER); 
    } 
    return *this;  
} 
0

Set不關心其中元素的索引,只關心元素是否在集合中。因此Rooms[i]不存在,並且您不能超載運算符[]進行設置。