【发布时间】:2016-08-19 18:52:32
【问题描述】:
以下代码对于重载比较运算符是否正确?这段代码中是否有任何愚蠢的错误或循环漏洞?我特别怀疑 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();
}
【问题讨论】:
标签: c++ operator-overloading pass-by-reference