这个函数的运算符参数太多

Operator(s) too many parameters for this function?

本文关键字:参数 太多 运算符 函数      更新时间:2023-10-16

制作了我自己的字符串类(即显然是为了作业),并且我在两个操作符上得到了奇怪的语法错误。我的相等和添加操作符声称我有太多的参数(即在我的。h文件中),但随后声称该方法甚至不属于我的。cpp文件中的类!

我甚至把相等运算符当作朋友,但是智能感知仍然给我相同的错误消息。

有人知道我做错了什么吗?

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

string.h

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

string.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;
}

您需要在类之外定义operator==:

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

如果operator+也是友元,它也需要被定义为自由函数(即在类之外)