1

andを実装し、 、、IEquatable<T>およびIComparable<T>をオーバーライドするクラスをC# から C++/CLI に移植しています。これまでのところ、私は持っています:==!=<>

ヘッダ:

virtual bool Equals(Thing other);
virtual int CompareTo(Thing other);

static bool operator == (Thing tc1, Thing tc2);
static bool operator != (Thing tc1, Thing tc2);
static bool operator > (Thing tc1, Thing tc2);
static bool operator < (Thing tc1, Thing tc2);

ソースファイル:

bool Thing ::Equals(Thing other)
{
    // tests equality here
}

int Thing ::CompareTo(Thing other)
{
    if (this > other) // Error here
        return 1;
    else if (this < other)
        return -1;
    else
        return 0;
}

bool Thing ::operator == (Thing t1, Thing t2)
{
    return tc1.Equals(tc2);
}

bool Thing ::operator != (Thing t1, Thing t2)
{
    return !tc1.Equals(tc2);
}

bool Thing::operator > (Thing t1, Thing t2)
{
    // test for greater than
}

bool Thing::operator < (Thing t1, Thing t2)
{
    // test for less than
}

オリジナルがインターフェースで同等性をテストし、オペレーターで物事を比較した理由はわかりませんが、元の構造を維持しようとしています。

とにかく、マークされた行「error C2679: binary '>' : no operator found which takes a right-hand operand of type 'ThingNamespace::Thing' (or there is no acceptable conversion)」でコンパイルエラーが発生し、対応するエラーが2行下にあります。オーバーロードされた演算子の存在を検出しないのはなぜですか?

4

3 に答える 3

7

thisはポインタなので、逆参照する必要があります。

if ((*this) > other)
    return 1;
else if ((*this) < other)
    return -1;
else
    return 0;
于 2009-06-15T12:04:35.000 に答える
1
return (*this) == other ? 0 : ((*this) > other ? 1 : -1);
于 2009-06-15T12:13:19.410 に答える
0

アルルが言ったように、 this キーワードを逆参照する必要がありますが、補足として、オブジェクトを渡す代わりに、関数パラメーターで const 参照を使用する必要があります。

-C++ はすべてのオブジェクトを参照ではなく値で渡す (これは C# で発生することです) ため、参照を使用するとオーバーヘッドが削減されます。

-新しい比較演算子を明示的に指定しなくても、std::sort などの標準ライブラリの関数を使用できます。

于 2009-06-15T12:13:40.597 に答える