错误 C2679:二进制"==":找不到采用类型右侧操作数的运算符

error C2679: binary '==' : no operator found which takes a right-hand operand of type

本文关键字:操作数 运算符 类型 C2679 二进制 找不到 错误      更新时间:2023-10-16

我无法正常工作。我已经重载了我的"=="运算符,但仍然收到此错误。不太确定为什么它被抛出或如何修复它。任何帮助将不胜感激。

这是我的算法:

/* 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
}

调试器说 main 中的这一行是错误的来源:

// 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

不确定是否需要更多我的代码。如果需要,我会更新。

当你打电话时

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

binarySearch中,T person的类型是指针数组,Vconst char*。然后在身体里你做

searchValue == *list[mid]

这是const char*& == *person[x],这就是为什么你得到错误,因为没有operator==(const char*, X) X在哪里是什么*person[x]

您的模板类适用于类型 TV 。 在binarySearch函数中,获取类型为 T 的列表和类型为 V 的搜索值。 然后你比较它们:if (searchValue == *list[mid]) . 这就是错误所在,因为您可能尚未为类 T 实现一个 == 运算符,该运算符接受类型 V 的参数。

这个问题可以追溯到你的cout,你传入Person作为类型 Tconst char*作为类型 V 。 您的 Person 类的 == 运算符仅接受同样为 Person 类型的右操作数。 换句话说,在表达式 a == b 中,b必须是Person类型。

if (searchValue == *list[mid])行将 const V& 类型与 T 进行比较。V 是一个 C 字符串 (char* (,假设那个人是一个数组Person* T 是一个Person。您提供了const Person&, const Person&比较运算符,但代码需要const char*&, const Person比较运算符。要么提供这样的运算符,要么从binarySearch(person, "Mickey Mouse", 0, 7)表达式中的字符串创建一个 Person。

相关文章: