首页 > 解决方案 > 如何与私有嵌套类成为朋友

问题描述

我以为我可以这样做:

class TestA
{
private:
  class Nested
  {

  };
};

class TestB
{
public:
  friend class TestA;
  friend class TestA::Nested;
};

但我收到一个错误:

错误 C2248 'TestA::Nested':无法访问在类中声明的私有类

有没有办法与私有嵌套类成为朋友?我该怎么做?

尝试在 MSVC 2017 (C++17) 中编译 MSVC 6 项目时遇到此错误。我想它当时奏效了。

标签: c++c++17friend

解决方案


以同样的方式访问任何其他私人事物。你需要友谊的另一种方式:

class TestA
{
  friend class TestB; // <== this
private:
  class Nested
  {

  };
};

class TestB
{
public:
  friend class TestA;
  friend class TestA::Nested; // <== now we're a friend of TestA, so we can access it
};

推荐阅读