我是 C++ 的新手(来自 Java 和 C#),我正在尝试覆盖我的一个类中的 == 运算符,这样我就可以查看是否有 2 个对给定值具有相同值的对象属性(property)。我一直在谷歌搜索并尝试做一些有用的东西。我需要的是 == 运算符在 2 个对象具有相同的 _name
文本时返回 TRUE。
这是头文件:
//CCity.h -- city class interface
#ifndef CCity_H
#define CCity_H
#include <string>
class CCity
{
friend bool operator ==(CCity& a, CCity& b)
{
bool rVal = false;
if (!(a._name.compare(b._name)))
rVal = true;
return rVal;
}
private:
std::string _name;
double _x; //need high precision for coordinates.
double _y;
public:
CCity (std::string, double, double); //Constructor
~CCity (); //Destructor
std::string GetName();
double GetLongitude();
double GetLatitude();
std::string ToString();
};
#endif
在我的 main() 方法中:
CCity *cit1 = new CCity("bob", 1, 1);
CCity *cit2 = new CCity("bob", 2, 2);
cout<< "Comparing 2 cities:\n";
if (&cit1 == &cit2)
cout<< "They are the same \n";
else
cout << "They are different \n";
delete cit1;
delete cit2;
问题是我在 friend bool operator ==
block 中的代码永远不会执行。我觉得我在声明该运算符的方式或使用它的方式上做错了。
最佳答案
&
获取地址(你正在比较指针),当你真的想使用 *
取消引用时:
if (*cit1 == *cit2)
cout<< "They are the same \n";
无论如何,这里绝对没有使用指针的意义,更不用说愚蠢的指针了。
这是没有它们的样子(正确的方式):
CCity cit1("bob", 1, 1);
CCity cit2("bob", 2, 2);
cout<< "Comparing 2 cities:\n";
if (cit1 == cit2)
cout<< "They are the same \n";
else
cout << "They are different \n";
此外,正如 WhozCraig 所提到的,请考虑为您的 operator==
函数使用 const-ref 参数,因为它不应修改参数。
关于c++ - 比较同一类的 2 个对象(覆盖 == 运算符)c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14680190/