close
A friend class is a class that can access the private members of a class as though it were a member of that class.
we can define an entire class as a friend as follow :
class X
{
int a, b;
friend class F;
public:
X() : a(1), b(2) { }
}; class F
{
public:
void print(X& x)
{
cout << "a is " << x.a << endl;
cout << "b is " << x.b << endl;
}
}; int main()
{
X xobj;
F fobj;
fobj.print(xobj);
return 0;
}
We can just define a function of class as friend :
#include <iostream>
using namespace std; class X; class Y
{
public:
void print(X& x);
}; class X
{
int a, b;
friend void Y::print(X& x);
public:
X() : a(1), b(2) { }
};
void Y::print(X& x)
{
cout << "a is " << x.a << endl;
cout << "b is " << x.b << endl;
} int main()
{
X xobj;
Y yobj;
yobj.print(xobj);
return 0;
}
全站熱搜