我是新来的c + +(来自Java和C#),我试图在我的一个类中覆盖==运算符,所以我可以看看我是否有2个对象具有给定属性的相同值。我一直在做一堆谷歌搜索,并试图做出一些有用的东西。我需要的是==运算符在2个对象具有相同的_name
文本时返回TRUE。比较同一类的2个对象(覆盖==运算符)C++
这里的头文件:
//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 ==
块代码永远不会被执行。我觉得我在做我的宣言或者我是如何使用它的时候做错了什么。
+1,也没有在声明一个自由函数运算符,也非const引用参数,等等 – WhozCraig
啊任意点。现在我明白了。我(尝试)将指针传递给==。是的,我可以在不使用指针的情况下离开,但我需要在我的代码中的其他地方使用==,我将使用动态内存和指针。谢谢。 – CurtisHx