2

私は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 ==ブロック内のコードが実行されないことです。その演算子を宣言する方法、またはそれを使用する方法のいずれかで何か間違ったことをしているように感じます。

4

2 に答える 2

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が言及しているoperator==ように、引数を変更するべきではないため、関数にconst-refパラメーターを使用することを検討してください。

于 2013-02-04T04:06:26.010 に答える
3

このコードで:

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";
于 2013-02-04T04:06:32.827 に答える