Friend Function Implementation in C++ Programming
Questions:-
Create two classes DM and DB which store the value of distances. DM storesdistances in meters and centimeters and DB in feet and inches. Write a program
that can read values for the class objects and add one object of DM with another
object of DB. Use a friend function to carry out the addition operation. The object
that stores the results may be a DM or DB object, depending on the units in
which the results are required.
(Object Oriented Programming With C++ By Balaguruswamy)
Solutions
#include<iostream>
using namespace std;
class DB;
class DM
{
int metre;
int centi;
public:
void inputDM();
friend void Add(DM,DB);
};
class DB
{
int inch;
int feet;
public:
void inputDB();
friend void Add(DM,DB);
};
void DM::inputDM()
{
cout<<"\tEnter Value for Metre & Centi:"<<endl;
cin>>metre>>centi;
}
void DB::inputDB()
{
cout<<"Enter Value for Feet & Inch:"<<endl;
cin>>feet>>inch;
}
void Add(DM a,DB b)
{
a.inputDM();
b.inputDB();
float addm;
int br=0;
addm=a.metre+(a.centi/100)+(b.inch*0.0254)+(b.feet*0.3048);//Convert all given inputs into meter
while(1)
{
cout<<"\n\n\t****Choose The Following Units****\n";
cout<<"-Press 1 for Meter\n";
cout<<"-Press 2 for Centimeter\n";
cout<<"-Press 3 for Feet"<<endl;
cout<<"-Press 4 for Inch"<<endl;
cout<<"-Press 5 Exit"<<endl;
cin>>br;
if(br==5)
break;
else
{
switch(br)
{
case 1:cout<<"The result in Meter:"<<endl;
cout<<addm;
break;
case 2:cout<<"The result in Centimeter:"<<endl;
float cm=addm*100;//Convert it into Centimeter
cout<<cm;
break;
case 3:cout<<"The result in Feet:"<<endl;
float ft=addm*3.280839895013123;//Convert into feet from meter
cout<<ft;
break;
case 4:cout<<"The result in Inch:"<<endl;
float in=addm*39.37007874015748;//convert into Inch from meter
cout<<in;
break;
default:cout<<"\n Invalid Choice....!\n";
continue;
}
}
}
}
int main()
{
DM x;DB y;
Add(x,y);
return 0;
}





0 comments:
Post a Comment