Cur*_*sHx 2 c++ overriding class operator-keyword
我是c ++的新手(来自Java和C#),我试图在我的一个类中覆盖==运算符,所以我可以看到我是否有2个对象具有相同的给定属性值.我一直在做一堆谷歌搜索,并试图做一些有用的东西.我需要的是==运算符在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
Run Code Online (Sandbox Code Playgroud)
在我的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;
Run Code Online (Sandbox Code Playgroud)
问题是我的friend bool operator ==块中的代码永远不会被执行.我觉得我正在做出错误,无论是我如何宣布该操作符,或者我是如何使用它的.
&获取(你正在比较指针)的地址,当你真正想要取消引用时*:
if (*cit1 == *cit2)
cout<< "They are the same \n";
Run Code Online (Sandbox Code Playgroud)
无论如何,在这里使用指针绝对没有意义,更不用说愚蠢了.
这是没有它们的样子(正确的方式):
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";
Run Code Online (Sandbox Code Playgroud)
另外,正如WhozCraig所提到的,考虑为operator==函数使用const-ref参数,因为它不应该修改参数.