簡體   English   中英

不匹配operator == error,C ++

[英]No match for operator == error, C++

這真讓我煩惱。 我正在使用C ++重載比較運算符,我得到一個奇怪的錯誤,我不確定如何糾正。

我正在使用的代碼如下所示:

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

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

integershort [30]

==重載工作正常。 但是當我嘗試在!=體中使用它時,它告訴我==尚未定義。 我是C ++的新手,所以歡迎任何提示。

謝謝!

您正在嘗試比較指針和實例。 this是指向當前對象的指針,您需要先取消引用它。

無論如何,你已經提到過integer是一個短褲數組。 這可能意味着你不應該將它與==進行比較 - 你應該手動比較所有元素(當然,在檢查數組中元素的數量是否相同之后,以防它們可以部分填充)。 或者你可以使用Luchian建議的vector - 它有一個明確定義的operator==

像這樣(缺少星號)。

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

this有類型HugeInt* ,但你使用它就像它是HugeInt&

使用return !(*this == h); 而是:)

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

應該

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

此外,如果integer的類型為short[30] ,則比較將不會達到預期效果。 你需要逐個元素地進行比較,如果這是你想要的。

另外,我可以建議使用std::vector<short>而不是原始數組嗎?

重載的運算符處理對象而非指針(如下所示)。 您應該在不等式運算符中取消引用它:

return !(*this == h);

你也可以像下面那樣構造它:

return( !operator==( h ) );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM