我需要做一些逻辑比较并返回一个 bool 值答案。
这是 .cpp 文件中的代码:
bool MyString::operator==(const MyString& other)const
{
if(other.Size == this.Size)
{
for(int i = 0; i < this.Size+1; i++)
{
if(this[i] == other[i])
return true;
}
}
else
return false;
}
这是从 main.cpp 文件中调用的内容:
if (String1 == String4)
{
String3.Print ();
}
else
{
String4.Print ();
}
这里是我得到的编译错误:
error: request for member `Size` in `this`, which is of non-class type `const MyString* const`
error: no match for `operator[]` in `other[i]`
最佳答案
this
是一个指针,因此您必须取消引用它:
this->Size;
此外,我认为您的 operator==
逻辑存在缺陷 - 在这里,如果任何字符等于第二个字符串中相同位置的字符,它返回 true
。将循环更改为
for(int i = 0; i < this->Size+1; i++)
{
if(this[i] != other[i])
return false;
}
并用 return true;
代替代码的最后一部分(else
子句)来比较整个字符串。
正如 Seth 所提到的,您不能像上面那样在 this
上使用 operator[]
- 这样它就被视为数组(即 this[i]
实际上是 *(this + i)
- 所以不是你想的那样)。而是访问您的内部存储成员。
关于c++ - 逻辑比较 == 运算符重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10368280/