2012-04-08 85 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 
}