C++ :: Friend Function
Use Of Common Friend Function To Exchange The Private Value Of Two Classes.
#include /iostream.h/
class class2; //forward declaration
class class1
{
int val1;
public:
void indata(int a)
{
val1=a;
}
void display(void)
{
cout<< val1 << "\n";
}
friend void exchange(class1 &,class2 &); //common friend function
};
class class2
{
int val2;
public:
void indata(int a)
{
val2=a;
}
void display(void)
{
cout<< val2 << "\n";
}
friend void exchange(class1 &,class2 &); //common friend function
};
void exchange(class1 & x,class2 & y) //definition of friend
{
int temp=x.val1;
x.val1=y.val2;
y.val2=temp;
}
int main()
{
class1 c1;
class2 c2;
c1.indata(10);
c2.indata(20);
cout<< "value before exchange" << "\n";
c1.display();
c2.display();
exchange(c1,c2); //swapping
cout<< "value after exchange" << "\n";
c1.display();
c2.display();
return 0;
}
0 comments:
Post a Comment