2

File A.hpp:

struct foo
{
   int x;
} foo;

inline bool operator ==(const foo &lhs, const foo &rhs)
{
   /* ... */
}

File B.hpp

#include "A.hpp"

namespace SomeNamespace
{
   bool operator==(const foo &lhs, const foo &rhs)
   {
      /* ... */
   }

   /* ... */
   void someFunction(const foo &foo_instance1, const foo &foo_instance2)
   {
      CPPUNIT_ASSERT(foo_instance1 == foo_instance2);
   }
}

The compiler error for the line with the ASSERT is:

error: ambiguous overload for 'operator==' ...

So, the problem is that the compiler sees both comparison operators.

The definition in the global namespace of A.hpp and the definition in the SomeNamespace of B.hpp are ambiguous.

Why does the compiler not use the defintion in the SomeNamespace?

4

2 回答 2

2

您已经定义了两次相同的函数;你期望会发生什么?编译器SomeNamespace::operator==使用非限定名称查找和::operator==ADL 进行查找。由于两者具有完全相同的签名,因此编译器无法选择其中一个。

作为一般规则,类型的重载运算符应定义在与该类型相同的命名空间中,而不是其他位置。(如果重载的运算符采用两种不同的类型,在两个不同的命名空间中定义,我会将运算符放在全局命名空间中。但这种情况很少见。)

于 2013-09-12T12:33:59.267 回答
2

在您的程序operator==中定义为 Global namespace 和 Somenamespace。

因此,当您尝试访问时,operator==编译器无法解析要调用的函数,因为这两个函数具有相同的签名并且编译器都可以看到它们。

因此,要使用operator==在 SomeNamespace 中定义,您必须使用SomeNamespace::operator==,对于在 Global 命名空间中定义的运算符,您必须使用::operator==.

于 2013-09-12T12:51:29.100 回答