简体   繁体   English

将函数声明为不同名称空间中的内联好友

[英]Declaring a function as inline friend in different namespace

I have a class declared like this : 我有一个这样声明的类:

namespace nsp1
{

 class A
 {
  public :
   inline friend void DoSomething();

  private :
   A();

   int a;
 };

}

Like this, the function DoSomething() will be in the namespace nsp1. 这样,函数DoSomething()将位于名称空间nsp1中。 Is there a way to declare this function to have it both inline friend and outside of the namespace? 有没有一种方法可以声明此函数以使其具有内联好友和名称空间之外的内容?

Here is a solution: 这是一个解决方案:

 namespace nsp1
{
    class A;
}

inline void DoSomething(const nsp1::A & a);
 namespace nsp1
{

 class A
 {
  public :
   inline friend void ::DoSomething(const nsp1::A & a);

  private :
   A();

   int a;
 };

}

inline void DoSomething(const nsp1::A & a)
{
     std::cout<<a.a<<std::endl;//a.a is private!
}

It is not possible to do it in one go. 一口气做不到。 You first need to declare the namespace and function, then define the class which befriends the function, and then define the function. 您首先需要声明名称空间和函数,然后定义与函数友好的类,然后定义函数。

namespace nsp2
{
   void DoSomething();
}

namespace nsp1
{
   class A
   {
   public :
      friend void nsp2::DoSomething();

   private :
      A();

      int a;
   };
}

namespace nsp2
{
   inline void DoSomething()
   {
      nsp1::A a;
      a.a = 42;
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM