私はc++(JavaとC#から来ています)に不慣れで、クラスの1つで==演算子をオーバーライドしようとしているので、特定のプロパティに同じ値を持つ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
私の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 ==
ブロック内のコードが実行されないことです。その演算子を宣言する方法、またはそれを使用する方法のいずれかで何か間違ったことをしているように感じます。