I have no clue how to do this i've been working on it for hours. There is only one example of friend classes in my textbook.
This is the question"Construct a class named Coord containing two double-precision variables named xval and yval, used to store the x and y values of a point in rectangular coordinates. The class methods should include constructor and display methods and a friend function named convPol(). The convPol() function should accept two double-precision numbers, r and theta, representing a point in polar coordinates and convert them into rectangular coordinates. For conversion from polar to rectangular coordinates, use these formulas: x = r cos(theta) y = r sin(theta)"
This is what i've come up with but I know i'm doing it wrong I just don't have a good reference point since there's only one lousy example in the whole textbook and is almost completely different. to be more specific I don't know where to use coord&(how to reference the number) and I know I shouldn't have used pointers. Can somebody point me in the right direction please?
This is my code:
#include <iostream>
#include <cmath>
using namespace std;
//ƒclassƒdeclarationƒsection
void ConvPol(double r,double theta, double& xval, double& yval)
{
double x,y;
xval=r*cos(theta);
yval=r*sin(theta);
return;
}
class Coord
{
//ƒfriendsƒlist
friend double ConvPol(Coord&);
private:
double xval;
double yval;
public:
Coord (double = 0, double = 0); //ƒconstructor
void display();
};
//ƒclassƒimplementationƒsection
Coord::Coord(double x, double y)
{
xval = x;
yval = y;
}
void Coord::display()
{
cout <<xval<<","<<yval;
return;
}
//ƒfriendƒimplementations
void time(double, double, double&, double&);
int main()
{ double xval,yval;
ConvPol(1,5,xval,yval);
Coord a(xval,yval);
a.display();
return 0;
}
Looks like you are confused. Here's my understanding:
class Coord
{
friend void ConvPol(Coord& point,
double rho, // length
double angle);
};
void ConvPol(Coord& point, double rho, double angle)
{
point.x = rho * cos(angle); // Assign to the point member x
point.y = rho * sin(angle); // Assign to the point member y.
}
According to the requirements, the ConvPol
function converts from polar coordinates (rho, angle) to Cartesian coordinates (x,y). So, the function needs rho
and angle
.
Since the function is free-standing (not in a method), it needs a Coord
instance to receive the converted values. It is passed by reference because the parameter will be modified (per the contents of the function).
The function does not return anything, so it has a return type of void
.
Because the function is a friend
of Coord
, the function can access the data members directly as if there wasn't any access rights (like a struct
).