二进制==的问题

Problem with binary ==

本文关键字:问题 二进制      更新时间:2023-10-16

我遇到了二进制operator==的奇怪问题。
我有一个函数返回:Type< Colors >* get();Tenum Colors {Red,Black}型我有一个operator==定义为:

bool operator==(Type<Colors>* left, Colors right)
{
//...
}
现在,在代码中我有行:
if (get() == Red)
{
//
}

但是在这里我得到错误说:

error C2679: binary '==' : no operator found which takes a right-hand operand of type 'Colors' (or there is no acceptable conversion)
1>          could be 'built-in C++ operator==(Node<Key_T,Value_T> *, Node<Key_T,Value_T> *)'
1>          with
1>          [
1>              Key_T=int,
1>              Value_T=int
1>          ]
or       'bool operator ==(const Type<T> *,const Colors)'
1>          with
1>          [
1>              T=Colors
1>          ]
1>          while trying to match the argument list '(Node<Key_T,Value_T> *, Colors)'
1>          with
1>          [
1>              Key_T=int,
1>              Value_T=int
1>          ]

显然第二个匹配是我打算使用的,它是完美匹配的,但它不想;)编译。我做错了什么?

(这比答案本身更具有诊断性…但是评论太多了

适用于GGC 4.5.2:

enum Colour { Red, Black };
template <typename T>
struct Type { };
bool operator==(Type<Colour>*, Colour) { return true; }
int main()
{
    Type<Colour>* p;
    return p == Black;
}

请在您的编译器上尝试上面的错误信息,如果有,请发布错误信息。如果没有,请发布你的确切完整的程序,因为错误可能是一些微妙的东西,你没有发布。

功能operator==既不修改左也不修改右?

输入const,就可以了