What area does C ++ live in?

I have some (real world) code that has a structure basically like this:

class C
   {
   public:
      C(int x = 0) : m_x(x) {}
      friend int foo(const C& c, int y) { return c.m_x + y; }
   private:
      int m_x;
   };

class Z
   {
   public:
      int foo(int y) {
        // The problematic call:
        return foo(c, y);
      }
   private:
      C c;
   };

I understand that the call fooinside Z::foomust be ambiguous. I don’t understand which area is suitable? I expected the C-friend declaration to foobe in the global namespace, but the call ::foodoes not work, and both GCC and Clang report this as an error.

However, if I change the C+ friend declaration to:

class C
   {
   public:
      C(int x) : m_x(x) {}
      friend int foo(const C& c, int y);
   private:
      int m_x;
   };

   int foo(const C& c, int y) { return c.m_x + y; }

Everything works, I can (c Z::foo) reference ::foo.

, : , C -friend foo in, ? foo Z::foo? ?

+4

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


All Articles