1

次の C++ プログラムで operator == を使用すると、問題が発生します。

#include < iostream>
using namespace std;

class A
{
    public:
        A(char *b)
        {
            a = b;
        }
        A(A &c)
        {
            a = c.a;
        }
        bool operator ==(A &other)
        {
            return strcmp(a, other.a);
        }
    private:
        char *a;
};


int main()
{
    A obj("test");
    A obj1("test1");

    if(obj1 == A("test1"))
    {
        cout<<"This is true"<<endl;
    }
}

行の何が問題になっていif(obj1 == A("test1"))ますか?? どんな助けでも大歓迎です。

4

4 に答える 4

34

strcmp文字列が等しい場合は 0 を返すため、次のようにします。

return strcmp(a, other.a) == 0;

Andreas Brinck がコメントで述べているようにconst、オペレーターで一時オブジェクトを使用できるため、Cătălin Pitiş が彼の回答で述べているような参照も使用する必要があります。const下。したがって、あなたの方法は次のようになります。

bool operator ==(const A &other) const
{
        return strcmp(a, other.a) == 0;
}
于 2009-12-07T13:46:53.667 に答える
3
bool operator ==( const A &other)

const 参照を使用するため、if ステートメントで構築される一時オブジェクトを operator== のパラメーターとして使用できます。

于 2009-12-07T13:46:16.057 に答える
2

オペレーターでこれが必要なようです:

strcmp(a, other.a) == 0

strcmp文字列が一致する場合は 0 を返し、比較がそれ以外の場合よりも大きいか小さいかを示す数値を返します。

于 2009-12-07T13:47:49.020 に答える
-1

エラーは、インスタント値を作成し、それをoperator==メソッドへの参照として渡すことです。しかし、あなたのエラーはあなたのオペレータ定義にあります:

bool operator==(const A& other) const

体は同じです。

于 2009-12-07T13:47:58.193 に答える