是否可以在C ++中为匿名命名空间中的类添加朋友? [英] Is it possible to friend a class in an anonymous namespace in C++?

查看:80
本文介绍了是否可以在C ++中为匿名命名空间中的类添加朋友?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将代码从Java移植到c ++,并且我想复制一些匿名功能.

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

在文件A.h中,我有:

In file A.h I have :

class A
{
private:
  int a;

  class AnonClass;
  friend class AnonClass;
};

在A.cpp文件中,我有:

In file A.cpp I have :

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

是否可以在C ++中为匿名命名空间中的类添加朋友?

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

在Java中,您可以声明匿名类,因此它非常相似.同样,它也不会将AnonClass暴露给A.h的客户端

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

推荐答案

鲜为人知的替代方法是使Anon类成为A的成员类.在A类内部,您只需要一行class Anon;-无需实际代码,无需朋友宣言.请注意,它进入类A中,几乎与Java中一样.在.cpp文件中,您编写了有关Anon的所有详细信息,但您并未将其放在匿名名称空间中,而是放在了A::

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

您可以像往常一样拆分A :: Anon的声明和实现,只是记住始终将A ::添加到Anon.

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

Anon类是A的成员,因此可以访问A的所有其他成员.但是对于A的客户来说,它仍然是未知的,并且不会使全局名称空间混乱.

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.

这篇关于是否可以在C ++中为匿名命名空间中的类添加朋友?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆