[C++] Ce este o clasa/functie 'friend' in C++?

Despre limbajul de programare C++ si biblioteca standard STL (forum moderat)
Post Reply
User avatar
Ovidiu Cucu
Fondator
Fondator
Posts: 3776
Joined: 11 Jul 2007, 16:10
Judet: Iaşi
Location: Iasi
Contact:

[C++] Ce este o clasa/functie 'friend' in C++?

Post by Ovidiu Cucu » 16 Jun 2011, 11:44

Intrebare
Ce este o clasa/functie friend?

Raspuns
Un friend al unei clase este o functie sau o clasa care are dreptul sa acceseze membrii private si protected ai acelei clase fara ca sa fie el insusi un membru.

Exemplu

Code: Select all

#include <iostream>

class A
{
public:
   A(int i) : m(i) {}
   // declare class B as friend of class A
   friend class B;
    // declare function g_print_m as friend of class A
   friend void g_print_m();
private:
   int m;
};

class B
{
public: 
   void print_m() 
   {
      A a(777);
      std::cout << "class B is a friend of class A" << std::endl
         << "so can access A::m private member" << std::endl  
         << a.m << std::endl;
   }
};

void g_print_m()
{
   A a(888);
   std::cout << "function g_print_m is not member of class A but is a friend" << std::endl
      << "so can access A::m private member: " << std::endl  
      << a.m << std::endl;
}

int main()
{
   B b;
   b.print_m();
   g_print_m();
   return 0;
}



Post Reply