I want to find the distance between two points. In class point
, the parameterized constructor, point(int a, int b)
, takes two integers and assigns them to the private variables, x
and y
. The displaypoint()
member function prints "(x,y)". It also has friend class, dist
.
The class dist
has only a constructor that takes two point
class objects as arguments and should display a calculated diff
variable.
However, my dist
class gives an error.
Here's the code.
// Parameterized Constructor using Friend Class Example :-
#include <iostream>
#include <cmath>
using namespace std;
class point
{
int x, y;
friend class dist;
public:
point(int a, int b)
{
x = a;
y = b;
}
void displayPoint()
{
cout << "The Point is : (" << x << "," << y << ")" << endl;
}
};
class dist // shows error here
{
public:
void dist(point p1, point p2)
{
int x_diff = (p2.x - p1.x);
int y_diff = (p2.y - p1.y);
int diff = sqrt(pow(x_diff, 2) + pow(y_diff, 2));
cout << "The difference is : " << diff << endl;
}
};
int main()
{
point p(1, 2);
point q(4, 6);
point c(1, 1);
point d(1, 1);
point e(1, 0);
point f(70, 0);
dist(p, q);
dist(c, d);
dist(e, f);
return 0;
}
If I remove class dist and make dist() as a friend function instead of a constructor, the code works.
void dist(point p1, point p2)
{
int x_diff = (p2.x - p1.x);
int y_diff = (p2.y - p1.y);
int diff = sqrt(pow(x_diff, 2) + pow(y_diff, 2));
cout << "The difference is : " << diff << endl;
}