繁体   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