Create friend square() function for Measure - C++ Class

C++ examples for Class:friend

Description

Create friend square() function for Measure

Demo Code

#include <iostream>
using namespace std;
class Measure// www. j a  v a 2s . c om
{
private:
  int feet;
  float inches;
public:
  Measure() : feet(0), inches(0.0)
  {  }
  Measure(int ft, float in) : feet(ft), inches(in)
  {  }
  void showdist()
  {
    cout << feet << "\'-" << inches << '\"';
  }
  friend float square(Measure);    //friend function
};
float square(Measure d)          //return square of
{                              //this Measure
  float fltfeet = d.feet + d.inches / 12;  //convert to float
  float feetsqrd = fltfeet * fltfeet;    //find the square
  return feetsqrd;               //return square feet
}
int main()
{
  Measure dist(3, 6.0);         //two-arg constructor (3'-6")
  float sqft;
  sqft = square(dist);           //return square of dist  and square
  cout << "\nMeasure = "; dist.showdist();
  cout << "\nSquare = " << sqft << " square feet\n";
  return 0;
}

Result


Related Tutorials