0

宿題がうまくできなくて困っています。「==」演算子をオーバーロードしましたが、それでもこのエラーが発生します。なぜスローされているのか、それを修正する方法はよくわかりません。どんな助けでも大歓迎です。

これが私のアルゴリズムです:

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

オーバーロードされた演算子を示す私の person クラスのヘッダー ファイルは次のとおりです。

#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

私のコードがさらに必要かどうかはわかりません。必要に応じて更新します。

4

3 に答える 3

3

電話すると

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

ではbinarySearchTの型はpersonポインターの配列であり、Vですconst char*。それからあなたがする体の中で

searchValue == *list[mid]

これは、どこに何がconst char*& == *person[x]あるかがないため、エラーが発生する理由です。operator==(const char*, X)X*person[x]

于 2013-03-10T22:30:31.283 に答える
0

テンプレートクラスはタイプTとのためのものVです。binarySearch関数では、タイプのリストとタイプTの検索値を取得しますV。次に、それらを比較しますif (searchValue == *list[mid])。これはエラーが発生する場所です。おそらく、型の引数を受け取る==クラスの演算子を実装していないためです。TV

問題は、あなたがタイプとして、そしてタイプとしてcout渡すあなたのにまでさかのぼることができます。クラスの演算子は、タイプも右辺のオペランドのみを取ります。つまり、式では、は型である必要があります。PersonTconst char*VPerson==Persona == bbPerson

于 2013-03-10T22:32:31.707 に答える
0

この行if (searchValue == *list[mid])は、型 const V& を T と比較します。V は C 文字列 ( ) であり、 person がTchar*の配列であると仮定すると、 a . 比較演算子を指定しましたが、コードでは 比較演算子が必要です。そのような演算子を提供するか、式の文字列から Person を作成します。Person*Personconst Person&, const Person&const char*&, const PersonbinarySearch(person, "Mickey Mouse", 0, 7)

于 2013-03-10T22:41:06.007 に答える