3

独自の文字列クラスを作成しました (つまり、明らかに宿題のため)、2 つの演算子で奇妙な構文エラーが発生しています。私の equality 演算子と add 演算子は、パラメーターが多すぎる (つまり、.h ファイルにある) と主張していますが、そのメソッドは .cpp ファイルのクラスに属していないと主張しています!

等値演算子も友達にしましたが、インテリセンスはまだ同じエラー メッセージを表示します。

誰かが私が間違っていることを知っていますか??

friend bool operator==(String const & left, String const & right);

文字列.h

bool operator==(String const & left, String const & right);
String const operator+(String const & lhs, String const & rhs);

文字列.cpp

bool String::operator==(String const & left, String const &right)
{
    return !strcmp(left.mStr, right.mStr);
}

String const String::operator+(String const & lhs, String const & rhs)
{
    //Find the length of the left and right hand sides of the add operator
    int lengthLhs = strlen(lhs.mStr);
    int lengthRhs = strlen(rhs.mStr);

    //Allocate space for the left and right hand sides (i.e. plus the null)
    char * buffer = new char[lhs.mStr + rhs.mStr + 1];

    //Copy left hand side into buffer
    strcpy(buffer, lhs.mStr);

    //Concatenate right hand side into buffer
    strcat(buffer, rhs.mStr);

    //Create new string
    String newString(buffer);

    //Delete buffer
    delete [] buffer;

    return newString;
}
4

1 に答える 1

4

operator==クラス外で定義する必要があります。

bool String::operator==(String const & left, String const &right)
     ^^^^^^^^ REMOVE THIS

もフレンドである場合operator+は、それもフリー関数として (つまり、クラスの外で) 定義する必要があります。

于 2013-04-18T05:47:41.203 に答える