c++ - 此代码对于重载比较运算符是否正确?

标签 c++ operator-overloading pass-by-reference

下面的代码重载比较运算符是否正确?这段代码中是否存在任何愚蠢的错误或循环漏洞?我特别怀疑if循环是if (b1 == b2)还是if (&b1 == &b2)?我认为哪一个是正确的,最终通过引用正确。如果我们在堆上分配对象,我们可以比较指针吗?

代码如下:

#include <QCoreApplication>
#include <iostream>

using namespace std;

class Base{
private:
    //static const int i=10;
    int j;
    string str;
public:
    //void display() const;
    //int read();
    bool operator==(const Base &rhs);
};

bool Base::operator ==(const Base &rhs)
{
    if((this->j == rhs.j) && (this->str == rhs.str))
        return true;
    else
        return false;
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    Base b1, b2;
    if(&b1 == &b2) // or if(b1 == b2)
    {
        cout << "Equal\n";
    }
    else
    {
        cout << "Not equal\n";
    }
    return a.exec();
}

最佳答案

此函数签名告诉编译器比较运算符可以更改对象值,因此不能在 const 对象上调用它。所以最好将它声明为 const:

bool operator==(const Base &rhs) const;

在此代码中,您正在比较两个对象的地址:

if(&b1 == &b2) // or if(b1 == b2)
{
    cout << "Equal\n";
}
else
{
    cout << "Not equal\n";
}

它们显然不相等。 if (b1 == b2) { ... } 如果您想检查对象是否相等,则正确。

What about if we allocate objects on heap, can we compare pointers?

如果 a 和 b 是指针,您可以比较指针值:

*a == *b 

或显式调用 operator==(丑陋的地方):

a->operator==(*b)

在 C++ 中,将此类运算符声明为友元很常见(但在您的情况下,这不是必需的)。在此代码中使用 this 也不会提高可读性。我希望将此运算符视为:

bool Base::operator == (const Base & rhs) const
{
    return j == rsh.j and str == rhs.str;
}

作为一般注意事项,因为该类称为 Base,您可能还需要将其声明为虚拟的。

添加:同样在这种情况下,j 将不会被初始化。修复它的最简单方法是在声明中添加初始值设定项:

class Base {
private:
    int j = 0;
    string str;
// ...
};

关于c++ - 此代码对于重载比较运算符是否正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36856538/

相关文章:

c++ - 错误 : overloaded 'operator<<' must be a binary operator (has 3 parameters)

c++ - 当它绑定(bind)到调用函数中的 const 引用时,它的返回值的生命周期如何扩展到调用函数的范围?

c++ - OpenCV 通过引用或指向回调函数的指针传递值

c++ - 将 1 到 100 之间的数字相加 OpenMP

c++ - 如何使用 WTL 获取编辑控件的内容?

c++ - 将 vector 拆分为唯一和重复 C++

c++ - 重载运算符 << undefined reference

c++ - 将 operator<< 与 const 对象一起使用

c++ - 在 C++ 中,如果我通过引用将 CString 传递给函数并将其分配给另一个 CString,它将被截断

C++ Libssh -sever/client file transfer over the lan 例子