Strange behavior with an operator defined as a friend inside the class

I do not understand what happens in the following code fragment:

struct A { };

struct B {
  B() { }
  B(const A&) { }

  friend B operator*(const B&, const B&)
  {
    return B();
  }
};

int main()
{
  B x = A() * A();

  return 0;
}

When I compile (with both clang and gcc 4.9.2), I get an error message in the line "B x = A () * A ()"; clang says "invalid operands for binary expression".

If I take the definition of the * operator inside the class, everything is 100% normal!

struct A { };

struct B {
  B() { }
  B(const A&) { }

  friend B operator*(const B&, const B&);
};

B operator*(const B&, const B&)
{
  return B();
}

int main()
{
  B x = A() * A();

  return 0;
}

What's happening?

+4
source share
1 answer

operator*() , ADL, . , , , . , , A B.

, .

+3

Source: https://habr.com/ru/post/1613913/


All Articles