2012-04-08 102 views
2

對於檢查簡單數組中的相等性,我有以下幾點:檢查數組中的元素是否相等 - C++

int a[4] = {9,10,11,20}; 
    if(a[3]== 20){ 
     cout <<"yes"<< endl; 
    } 

但是,當我創建一個類型數組的數組,並嘗試和檢查相等我得到錯誤;

人類是一個具有名稱,年齡,性別等私有變量的類,併爲這些變量獲取和設置函數。

humanArray有大小20

void Animal::allocate(Human h){ 
    for (int i =0; i<20; i++){ 
     if(humanArray[i] == h){ 
      for(int j = i; j<size; j++){ 
       humanArray[j] = humanArray[j +1]; 
      } 
     } 
    } 
} 

我得到下面的錯誤;

error: no match for 'operator==' in '((Animal*)this)->Animal::humanArray[i] == h'| 

我可以通過索引和人類,並檢查索引號。但是,有沒有辦法檢查兩個元素是否相同?我不想檢查對人名說'人名',因爲在某些地方我的人不會有名字。

回答

6

爲了使語法

if(humanArray[i] == h) 

法律,你需要定義operator==你的人類。要做到這一點,你可以編寫一個函數,看起來像這樣:

bool operator== (const Human& lhs, const Human& rhs) { 
    /* ... */ 
} 

在這個函數中,你會做的lhsrhs場逐場比較,看看他們都是平等的。從這一點開始,任何時候,如果您嘗試使用==運算符來比較任何兩個人,C++將自動調用此函數進行比較。

希望這會有所幫助!

0

你需要重載operator==的類人

bool operator== (const Human& left, const Human& right) 
{ 
// perform comparison by each element in the class Human 
}