下面的代码重载比较运算符是否正确?这段代码中是否存在任何愚蠢的错误或循环漏洞?我特别怀疑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/