2

This is really bugging me. I'm working on overloading the comparison operators in C++, and I'm getting a weird error that I'm not sure how to correct.

The code I'm working with looks like this:

bool HugeInt::operator==(const HugeInt& h) const{
    return h.integer == this->integer;
}

bool HugeInt::operator!=(const HugeInt& h) const{
    return !(this == h);
}

where integer is a short [30]

The == overloading works fine. But when I try to use it in the != body, it tells me that == has not been defined. I'm new to C++, so any tips are welcome.

Thanks!

4

5 に答える 5

12

ポインタとインスタンスを比較しようとしています。thisは現在のオブジェクトへのポインタです。最初にそれを逆参照する必要があります。

とにかく、あなたはそれintegerがショーツの配列であると言いました。これはおそらく、それを比較するべきではないことを意味します==-すべての要素を手動で比較する必要があります(もちろん、部分的に埋めることができる場合は、配列内の要素の数が同じであることを確認した後)。vectorまたは、Luchianが提案したようにを使用することもできます-それは明確に定義されていoperator==ます。

于 2012-10-25T20:48:55.060 に答える
5

このように(アスタリスクがありません)。

bool HugeInt::operator!=(const HugeInt& h) const{
    return !(*this == h);
}
于 2012-10-25T20:49:18.240 に答える
4

thisタイプHugeInt*はですが、のように使用しますHugeInt&

return !(*this == h);代わりに使用してください:)

于 2012-10-25T20:49:00.877 に答える
2
bool HugeInt::operator!=(const HugeInt& h) const{
    return !(this == h);
}

する必要があります

bool HugeInt::operator!=(const HugeInt& h) const{
    return !(*this == h);
}

また、integerが typeshort[30]の場合、比較は期待どおりに行われません。それが必要な場合は、要素ごとに比較する必要があります。

std::vector<short>また、生の配列の代わりに aを使用することをお勧めしますか?

于 2012-10-25T20:49:30.913 に答える
2

オーバーロードされた演算子は、ポインターではなくオブジェクトで機能します (このように)。不等式演算子でこれを逆参照する必要があります。

return !(*this == h);

または、次のように構成することもできます。

return( !operator==( h ) );
于 2012-10-25T20:52:05.897 に答える