逻辑比较 == 运算符重载

Logical Comparison == operator overload

本文关键字:运算符 重载 比较      更新时间:2023-10-16

我需要做一些逻辑比较并返回一个布尔答案。

以下是.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;
}

这是从主文件调用的内容.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) - 所以不是你想的那样)。请改为访问您的内部存储成员。

代码问题:

  • this[i]:您显然想在此处访问字符串的第 i 个字符。这不是这样做的。假设你的类重载operator[],你需要(*this)[i]。或者,您可以直接访问字符串的内部表示形式。

  • if(this[i] == other[i]) return true; : 想想这对比较字符串"A1"和"AB"意味着什么。

  • for () {...} : 退出循环时会发生什么?如果比较设法通过循环而不返回,则需要返回一些内容。

您尚未指定是否可以使用C++标准算法。在这里,您已经说明了使用手写循环和std::equal算法的两个版本:

//#define USE_STD_ALGORITHM 1 // uncomment to enable std::equal version
#include <cassert>
#include <algorithm>
#include <stdexcept>
// NOTE: partial simplest definition for the test and presentation purposes only.
struct MyString
{
    MyString(char const* s, std::size_t size) : data(s), Size(size) {}
    char const& operator[](std::size_t index) const;
    bool operator==(const MyString& other) const;
private:
    char const* data;
    std::size_t Size;
};
char const& MyString::operator[](std::size_t index) const
{
    if (index < Size)
        return data[index];
    throw std::out_of_range("index invalid");
}
bool MyString::operator==(const MyString& other) const
{
    if (this->Size == other.Size)
    {
#ifdef  USE_STD_ALGORITHM
        return std::equal(data, data+Size, other.data);
#else
    bool equal = true;
    for(std::size_t i = 0; i < this->Size; ++i)
    {
        if((*this)[i] != other[i])
        {
            equal = false;
            break;
        }
    }
    return equal;
#endif
    }
    return false;
}
int main()
{
    char const* a = "abc";
    char const* b = "abc";
    MyString sa(a, 3);
    MyString sb(b, 3);
    assert(sa == sb);
    char const* c = "adc";
    MyString sc(c, 3);
    assert(!(sa == sc));
    char const* d = "ab";
    MyString sd(d, 2);
    assert(!(sa == sd));
}

祝你好运!