简体   繁体   中英

How to access private member function using friend class object?

In main , I want to access the display function. Here, in class B I declared class A as friend. So i thought that it is possible to access the private member functions. But i dont know how to do that.

#include<stdio.h>

class A
{ 
  public:
  class B
  {
    public:
     friend class A;
    private:
     void display()
     {
       printf("\nHi");
     }
  };
};

int main()
{
  //here i wanna access display function.. is it possible?
  return 1;
}

friend specifies what has access to private members. In your case, you want to access private members in the main function, so you should specify that it's friend:

class A
{ 
    public:
    class B
    {
       friend int main();
       void display()
       {
           printf("\nHi");
       }
    };
};

int main()
{
    // here you can access display function:
    A::B object;
    object.display();
}

Alternatively, if you want to make class A (and not anything else) a friend, then class A should access the display function. Any member of class A can do it:

class A
{ 
    public:
    class B
    {
       friend class A;
       void display()
       {
           printf("\nHi");
       }
    };

    // here you can access display function:
    void access_display(B object)
    {
        object.display();
    }
};

int main()
{
    A object1;
    A::B object2;
    object1.access_display(object2);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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