
Question:
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(); } } 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.
Solution:1
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 }
Solution:2
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(); }
Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
EmoticonEmoticon