开发者

Friend function cannot access private function if class is under a namespace

I have a class inside a namespace and that class contains a private function. And there is a global function. I want that global function to be the friend of my class which is inside the namespace. But when I make it as a friend, the compiler thinks that the function is not global and it is inside that namespace itself. So if I try to access the private member function with global function, it doesn't work, whereas if I define a function with the same name in that namespace itself it works. Below is the code you can see.

#include <iostream>
#include <conio.h>

namespace Nayan
{
   class CA
   {
   private:
      static void funCA();
      friend void fun();
   };

   void CA::funCA()
   {
      std::cout<<"CA::funCA"<<std::endl;
   }

   void fun()
   {
      Nayan::CA::funCA();
   }开发者_StackOverflow中文版

}

void fun()
{
   //Nayan::CA::funCA(); //Can't access private member
}


int main()
{
   Nayan::fun();
   _getch();
   return 0;
}

I also tried to make friend as friend void ::fun(); And it also doesn't help.


You need to use the global scope operator ::.

void fun();

namespace Nayan
{
    class CA
    {
    private:
        static void funCA();
        friend void fun();
        friend void ::fun();
    };

    void CA::funCA()
    {
        std::cout<<"CA::funCA"<<std::endl;
    }

    void fun()
    {
        Nayan::CA::funCA();
    }

}


void fun()
{
   Nayan::CA::funCA(); //Can access private member
}


The fun() function is in the global namespace. You need a prototype:

void fun();

namespace Nayan
{
    class CA
    {
    private:
        static void funCA() {}
        friend void ::fun();
    };

}

void fun()
{
    Nayan::CA::funCA();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜