sum of feet and inches,meter and cm using Friend function with c++

Create two classes DM and DB which store the value of distances. DM stores distances 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 object or DB object, depending on the units in which the results are required. The display should be in the format of feet and inches or meters and centimeters depending on  the object on display.
1 Feet = 0.3048 Meter & 1 Meter = 3.28 Feet  
1 Inch = 2.54 Centimeter & 1 Centimeter = 0.3937 Inch

Use friend function: Use friend function is limited purpose,friendship is not mutual that means is class A friend of class B then class B does not become friend of class A automatically.

  • Friend function can be given special access to the private and protected member.
  • Friendship is not inherited.
  • Friend class :All member function of all class as friend function of another class. In such cases the class is called friend class.
  • In this friend function,one class of data member access on another class in private part then and then use friend function OR if we use of data member of first class to another class in member function then use friend function.
  • function is keyword.

Friend function syntax:
 
friend return_type class_name :: function();

what use of operator+:

overloaded operator are redefine in c++ class using keyword of operator follow by operator symbol.

operator function should be either member function or friend function.
friend function required one argument for unary operator and two argument fro binary operator.

It is essentially pass to object by value or reference.

process:


1 Feet = 0.3048 Meter & 1 Meter = 3.28 Feet  
1 Inch = 2.54 Centimeter & 1 Centimeter = 0.3937 Inch

in DB operator+ function ,
convert meter into cm and feet into inches and after summation of feet and inches with convert cm into inches.
   

coding:

#include<iostream>
using namespace std;
 class DB;
class DM
{
float meter,cm;
public:
DM()
{
}
DM(float a,float b)
{
meter=a;
cm=b;
}
friend DB operator+(DM,DB);
};
class DB
{
float feet,inches;
public:
DB()
{
}
DB(int x,int y)
{
feet=x;
inches=y;
}
void display()
{
cout<<"\n feet is:"<<feet;
cout<<"\n inches is:"<<inches;
}
friend DB operator+(DM,DB);
};
DB operator+(DM e,DB f)
{
DB ss;
e.cm+=e.meter*100;
f.inches+=f.feet*12;
ss.inches=e.cm*0.3937+f.inches;
if(ss.inches>=12)
{
ss.feet++;
ss.inches-=12;
}
return ss;
}
int main()
{
DM d1(10,20);
DB d2(12,13);
DB sd;
sd=d1+d2;
sd.display();
return 0;
}


output:



0 comments:

Copyright © 2013 free coding