C ++朋友的居住范围是什么?

时间:2018-02-18 17:21:37

标签: c++ scope friend

我有一些(现实世界)代码,其结构基本上如此:

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;
   };

我理解,fooZ::foo的调用需要消除歧义。我不明白的是,适当的范围是什么?我期望C - 朋友foo的声明在全局命名空间中,但调用::foo不起作用,GCC和Clang都将此报告为错误。

但是,如果我将C +朋友的声明更改为:

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; }

一切正常,我可以(在Z::foo中)引用::foo

所以这是我的问题:在第一个例子中,C - 朋友foo的范围是什么,如果它不在全局命名空间中?是否无法从foo内引用全球Z::foo?而且,我的第一个和第二个例子之间有什么区别?

0 个答案:

没有答案