这真的让我感到困惑。我正在努力超载C 中的比较运算符,并且我遇到了一个奇怪的错误,我不确定如何更正。
我正在使用的代码看起来像这样:
bool HugeInt::operator==(const HugeInt& h) const{
return h.integer == this->integer;
}
bool HugeInt::operator!=(const HugeInt& h) const{
return !(this == h);
}
其中 integer
是 short [30]
==
重载正常。但是,当我尝试在!=
主体中使用它时,它告诉我==
尚未定义。我是C 的新手,因此欢迎任何提示。
谢谢!
您正在尝试比较指针和实例。 this
是指向当前对象的指针,您需要先解释。
无论如何,您已经提到integer
是一系列短裤。这可能意味着您不应该将其与 ==
进行比较 - 您应该手动比较所有元素(当然,当然,您可以检查阵列中的元素数量是否相同,以防它们可以部分填充)。或者,您可以按照卢切安建议使用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 ) );