c++ - 逻辑比较 == 运算符重载

标签 c++ comparison operator-overloading

我需要做一些逻辑比较并返回一个 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/

相关文章:

javascript - CoffeeScript 中的测试对象相等性?

python - 比较两个图像(包含建筑物)的相似性的最有效方法是什么

c++ - 使用 operator<< 重载打印派生对象不起作用

C# 在类外重载运算符==

c++ - 重载子类

c++ - 类模板,如果对象是X类型的成员函数定义?

C++ std::thread 应该在堆上或堆栈上创建

c++ - OpenGL 3.3 MSAA 延迟着色

c# - 如何使用 API 调用重现 quser.exe?

c++ - 如果我们添加安全的有符号/无符号比较 C/C++,它会破坏语言或现有代码吗?