我是新來的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