MrP*_*le5 2 c++ operator-overloading
制作了我自己的字符串类(显然是为了家庭作业),并且我的两个运算符出现了奇怪的语法错误。我的相等和添加运算符声称我有太多参数(即在我的 .h 文件中),但随后又声称该方法甚至不属于我的 .cpp 文件中的类!
我什至将相等运算符设为朋友,但智能感知仍然给我相同的错误消息。
有谁知道我做错了什么?
friend bool operator==(String const & left, String const & right);
Run Code Online (Sandbox Code Playgroud)
字符串.h
bool operator==(String const & left, String const & right);
String const operator+(String const & lhs, String const & rhs);
Run Code Online (Sandbox Code Playgroud)
字符串.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;
}
Run Code Online (Sandbox Code Playgroud)
您需要operator==在类外定义:
bool String::operator==(String const & left, String const &right)
^^^^^^^^ REMOVE THIS
Run Code Online (Sandbox Code Playgroud)
如果operator+也是一个友元,它也需要被定义为一个自由函数(即在类之外)。
| 归档时间: |
|
| 查看次数: |
24656 次 |
| 最近记录: |