以下代码是否适用于重载比较运算符?这段代码中是否有任何愚蠢的错误或循环漏洞?我特别怀疑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();
}
在这两种情况下,我都变得不相等。如果内容相同,那么相等应该返回true对吗? – highlander141
在你的情况下,你正在比较两个对象什么没有被初始化。所以如果字符串默认初始化为空,那么我每次都会被垃圾初始化。 –
是的我有你的意思,如果我评论int和字符串,并且只比较静态常量,那么两个对象是相等的。 – highlander141