2013-03-10 117 views
0
類型的右側操作數

我無法讓我的作業分配正常工作。我重載了我的'=='運算符,但仍然出現此錯誤。不知道爲什麼它被拋出或如何解決它。任何幫助,將不勝感激。錯誤C2679:二進制'==':沒有找到操作符,它需要

這裏是我的算法:

/* Performs a recursive binary search on the given array. It returns 
* the index of the found value, -1 otherwise. 
*/ 
template <typename T, typename V> 
int binarySearch(T* list[], const V& searchValue, 
       const int firstIndex, const int lastIndex) 
{ 
    if (firstIndex <= lastIndex) 
    { 
     int mid = (firstIndex + lastIndex)/2; //mid point of list. 
     if (searchValue == *list[mid]) 
      return mid; // found value. 
     else if (searchValue < *list[mid]) 
      return binarySearch(list, firstIndex, mid - 1, searchValue); 
     else 
      return binarySearch(list, mid + 1, lastIndex, searchValue); 
    } 
    return -1; //failed to find value 
} 

調試器說,此行主要是在錯誤來源:

// Search the person array. 
cout << "Searching people array for person with name = 'Mickey Mouse': " 
    << (binarySearch(person, "Mickey Mouse", 0, 7) != -1? "found it." : "did not find it.") 
    << endl; 

這是我個人類的頭文件顯示重載操作符:

#ifndef PERSON_H 
#define PERSON_H 

#include <string> 
#include <iostream> 

using namespace std; 

namespace P03 { 
class Person {...}; // end Person 


/* Displays a Person to the screen. 
* Calls the toString() method. 
*/ 
ostream& operator <<(ostream& out, const Person& person) 
{ 
    return out << person.toString(); 
} 

/* The following relational operators compare two instances of the 
* Person class. The comparison is made on the compound value of: 
* <lastName><space><firstName> 
*/ 
bool operator ==(const Person& lhs, const Person& rhs) 
{ 
    return lhs.getName() == rhs.getName(); 
} 

    /*other operators*/ 
    ... 

} // end namespace P03 

#endif 

不知道是否需要更多我的代碼。如有需要,我會進行更新。

+0

我加了一個新的運營我的Person類的頭文件: '布爾運算符==(爲const char * LHS,常量人及右) \t { \t \t回LHS == rhs.getName(); \t}' 我仍然收到同樣的錯誤。也許我誤解了你給我的一些答案。 – user2069621 2013-03-10 23:36:36

回答

3

當調用

binarySearch(person, "Mickey Mouse", 0, 7) 

binarySearchT其中person是一個指針數組類型,並且Vconst char*。然後在身體,你做

searchValue == *list[mid] 

哪個const char*& == *person[x],這就是爲什麼你的錯誤,因爲沒有operator==(const char*, X)其中X是什麼*person[x]是。

+0

實際上,'person'是'T *'的數組,而不僅僅是'T'。但這個答案的本質看起來是正確的。 – 2013-03-10 22:37:19

+0

@BenVoigt哈,謝謝。糟糕的閱讀。 – 2013-03-10 22:49:08

0

您的模板類適用於TV類型。在binarySearch函數中,您將獲取類型爲T的列表以及類型爲V的搜索值。然後再比較它們:if (searchValue == *list[mid])。這是錯誤發生的地方,因爲您可能尚未實施類T==運算符,該運算符需要V類型的參數。

問題可以追溯到您cout,在那裏你在PersonT型和const char*作爲V型傳輸。您的Person類'==運營商只需要一個類型爲Person的右側操作數。換句話說,在表達式a == b中,b必須是Person類型。

0

if (searchValue == *list[mid])類型常量V &與T. V相比較是C-串(char*),並假定人的Person*陣列T爲Person。您提供了一個const Person&, const Person&比較運算符,但代碼需要const char*&, const Person比較運算符。可以提供這樣一個操作符,也可以使用binarySearch(person, "Mickey Mouse", 0, 7)表達式中的字符串創建一個Person。

相關問題