Write a C++ program to swap the value of private data members from 2 different classes.
CODING:
#include<iostream.h>
#include<conio.h>
class two;
class one
{
int a;
public:
one(int x)
{
a=x;
}
void disp()
{
cout<<a;
}
friend void swap(one &,two &);
};
class two
{
int b;
public:
two(int y)
{
b=y;
}
void disp()
{
cout<<b;
}
friend void swap(one &,two &);
};
void swap(one &o1,two &o2)
{
int temp=0;
temp=o1.a;
o1.a=o2.b;
o2.b=temp;
cout<<"\n1: "<<o1.a;
cout<<"\n2: "<<o2.b;
}
void main()
{
int a,b;
clrscr();
cout<<"Enter the number 1:";
cin>>a;
one o1(a);
cout<<"Enter the number 2:";
cin>>b;
two o2(b);
cout<<"Before Swaping:";
cout<<"\n1: ";o1.disp();
cout<<"\n2: ";o2.disp();
cout<<"\nAfter Swaping:";//call function.
swap(o1,o2);
cout<<"\nAfter Swaping:";//Refrence Value.
cout<<"\n1: ";o1.disp();
cout<<"\n2: ";o2.disp();
getch();
}
CODING:
#include<iostream.h>
#include<conio.h>
class two;
class one
{
int a;
public:
one(int x)
{
a=x;
}
void disp()
{
cout<<a;
}
friend void swap(one &,two &);
};
class two
{
int b;
public:
two(int y)
{
b=y;
}
void disp()
{
cout<<b;
}
friend void swap(one &,two &);
};
void swap(one &o1,two &o2)
{
int temp=0;
temp=o1.a;
o1.a=o2.b;
o2.b=temp;
cout<<"\n1: "<<o1.a;
cout<<"\n2: "<<o2.b;
}
void main()
{
int a,b;
clrscr();
cout<<"Enter the number 1:";
cin>>a;
one o1(a);
cout<<"Enter the number 2:";
cin>>b;
two o2(b);
cout<<"Before Swaping:";
cout<<"\n1: ";o1.disp();
cout<<"\n2: ";o2.disp();
cout<<"\nAfter Swaping:";//call function.
swap(o1,o2);
cout<<"\nAfter Swaping:";//Refrence Value.
cout<<"\n1: ";o1.disp();
cout<<"\n2: ";o2.disp();
getch();
}
Output
ReplyDelete