Is it possible to friend a class in an anonymous namespace in C++?

风格不统一 提交于 2020-12-29 02:41:13

问题


I am porting code from Java to c++ and I'd like to replicate some anonymous functionalities.

In file A.h I have :

class A
{
private:
  int a;

  class AnonClass;
  friend class AnonClass;
};

In file A.cpp I have :

namespace
{
  class AnonClass
  {
  public:
    AnonClass(A* parent)
    {
      parent->a = 0; // This doesn't work, a is not accessible
    }
  }
}

Is it possible to friend a class in an anonymous namespace in C++?

In Java you can declare anonymous classes so it would be very similar. Also it would not expose AnonClass to clients of A.h


回答1:


Less known alternative is to make class Anon a member class of A. Inside class A you only need a line class Anon; -- no real code, no friend declaration. Note it goes within class A, almost as in Java. In the .cpp file you write all the details about Anon but you put it not in anonymous namespace but withinA::

  class A::Anon { ..... };

You can split declaration and implementation of A::Anon, as usual, just remeber always add A:: to Anon.

The class Anon is a member of A and as such gets access to all other members of A. Yet it remains unknown to clients of A and does not clutter global namespace.




回答2:


As far as I can see you can not. The reasons:

  1. The “anonymous” namespace is accessible only within the file you created it in.
  2. You have to define whole AnonClass class and it's functions in one namespace, i.e. in one place in the program.
  3. Class A has to be defined before AnonClass constructor.
  4. AnonClass has to be at least declared before class A.

So you see, you can't break AnonClass definition on two parts. And you can't define it both before and after A class.

The only option - put class A into the same anonymous namespace. This code works:

namespace 
{
  class A
  {
   public:
    A():a(0){};
   private:
    int a;

    friend class AnonClass;
  };

  class AnonClass
  {
  public:
    AnonClass(A* parent);
  };

  AnonClass::AnonClass(A* parent)
  {
      parent->a = 0;
  };
}

int main() {
  A a;

  return 0;
}

I hope this helps.



来源:https://stackoverflow.com/questions/19872920/is-it-possible-to-friend-a-class-in-an-anonymous-namespace-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!