【问题标题】:C++ friend class of the same name in different levels of a nested namespace嵌套命名空间不同层级的同名C++友元类
【发布时间】:2017-05-03 13:09:42
【问题描述】:

不确定这是否可行,但我在嵌套命名空间的不同级别中有两个同名的类,我想让更浅的类成为更深的类的朋友。示例:

在 File1.h 中:

namespace A
{
  class Foo
  {
    //stuff
  };
}

在 File2.h 中:

namespace A
{
  namespace B
  {
    class Foo
    {
      friend class A::Foo; //Visual Studio says "Error: 'Foo' is not a member of 'A'"
    };
  }
}

这可能吗?如果是这样,正确的语法是什么?

【问题讨论】:

  • 您是否将File1.h 包含在File2.h 中?

标签: c++ namespaces friend friend-class


【解决方案1】:

这段代码放在一个文件中时编译正常(除了A::B::Foo类之后需要;):IdeOne example

因此,问题出在问题文本中未包含的代码中。可能#include "File1.h"File2.h 中被遗忘了。

【讨论】:

    【解决方案2】:

    如果你想避免将大的头文件包含到其他人中,你至少需要在使用它们之前转发声明你的类:

    namespace A
    {
      class Foo;
    
      namespace B
      {
        class Foo
        {
          friend class A::Foo;
        }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-17
      • 2019-08-03
      • 2011-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多