简体   繁体   English

不匹配operator == error,C ++

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

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. 我正在使用C ++重载比较运算符,我得到一个奇怪的错误,我不确定如何纠正。

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] integershort [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. 我是C ++的新手,所以欢迎任何提示。

Thanks! 谢谢!

You're trying to compare a pointer and an instance. 您正在尝试比较指针和实例。 this is a pointer to the current object, you need to dereference it first. this是指向当前对象的指针,您需要先取消引用它。

Anyway, you've mentioned that integer is an array of shorts. 无论如何,你已经提到过integer是一个短裤数组。 That probably means you shouldn't compare it with == - you should just compare all the elements manually (after, of course, you check that the number of elements in the arrays is the same, in case they can be filled partially). 这可能意味着你不应该将它与==进行比较 - 你应该手动比较所有元素(当然,在检查数组中元素的数量是否相同之后,以防它们可以部分填充)。 Or you could use a vector as Luchian suggested - it has a well-defined operator== . 或者你可以使用Luchian建议的vector - 它有一个明确定义的operator==

Like this (missing asterisk). 像这样(缺少星号)。

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

this has type HugeInt* , but you use it as if it is HugeInt& . this有类型HugeInt* ,但你使用它就像它是HugeInt&

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

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

should be 应该

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

Also, if integer is of type short[30] , the comparison won't do what you expect. 此外,如果integer的类型为short[30] ,则比较将不会达到预期效果。 You'll need to compare element by element, if that's what you want. 你需要逐个元素地进行比较,如果这是你想要的。

Also, might I suggest using a std::vector<short> instead of a raw array? 另外,我可以建议使用std::vector<short>而不是原始数组吗?

Overloaded operators work on objects not pointers (like this). 重载的运算符处理对象而非指针(如下所示)。 You should dereference this in your inequality operator: 您应该在不等式运算符中取消引用它:

return !(*this == h);

You could alternatively structure it like: 你也可以像下面那样构造它:

return( !operator==( h ) );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM