2013-02-04 44 views
1

我是新來的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 ==塊代碼永遠不會被執行。我覺得我在做我的宣言或者我是如何使用它的時候做錯了什麼。

回答

5

&需要的地址(你比較指針),當你真正使用*要取消引用:

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==功能,因爲它不應該修改的參數。

+0

+1,也沒有在聲明一個自由函數運算符,也非const引用參數,等等 – WhozCraig

+0

啊任意點。現在我明白了。我(嘗試)將指針傳遞給==。是的,我可以在不使用指針的情況下離開,但我需要在我的代碼中的其他地方使用==,我將使用動態內存和指針。謝謝。 – CurtisHx

2

有了這個代碼:

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";