#include <iostream>
using namespace Std;
Class MyClass1
{
Public:
MyClass1 (): N (0) {};
void Setn (int tmpn) {THIS->N=TMPN;}
void Show () {Cout<<n<<endl;}
Private
Friend class
Friend class MyClass2;
Use the friend function to change the value of the member variable n in the MyClass1
friend void SetnF1 (MyClass1 & Tmpclass,int TMPN);
int n;
};
Class MyClass2
{
Public
Use member functions in a friend class to change the value of member variable N in myclass1
void SetnF2 (MyClass1 & Tmpclass,int tmpn) {TMPCLASS.N=TMPN;}
};
void SetnF1 (MyClass1 & Tmpclass,int TMPN)
{
TMPCLASS.N=TMPN;
}
int main ()
{
MyClass1 P1;
MYCLASS2 P2;
cout<< "P1 member variable n defaults to:" <<endl;
P1.show ();
cout<< "after setting using MyClass1 's own member function:" <<endl;
P1.SETN (100);
P1.show ();
cout<< "after setting with friend function:" <<endl;
SetnF1 (p1,101);
P1.show ();
cout<< "After setting with friend class:" <<endl;
P2.setnf2 (p1,102);
P1.show ();
return 0;
}
Execution Result: (click image to enlarge)
Friend function and friend class in C + +