比较同一类的2个对象(覆盖==运算符)C++
问题描述:
我是新来的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 ==
块代码永远不会被执行。我觉得我在做我的宣言或者我是如何使用它的时候做错了什么。
答
&
需要的地址(你比较指针),当你真正使用*
要取消引用:
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提到,可以考虑使用常量-ref参数为您operator==
功能,因为它不应该修改的参数。
答
有了这个代码:
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";
你是比较指针到指针到CCity实例。
你想是这样的:
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";
+1,也没有在声明一个*函数运算符,也非const引用参数,等等 – WhozCraig
啊任意点。现在我明白了。我(尝试)将指针传递给==。是的,我可以在不使用指针的情况下离开,但我需要在我的代码中的其他地方使用==,我将使用动态内存和指针。谢谢。 – CurtisHx