2013-03-10 115 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。

相关问题