Need help with C++ program!!

Question: Create a class called XYPoint that has public floats to hold the x and y values of a 2D point. The class should have a constructor with default values (0,0) and a method called Distance( XYPoint ) that returns the Euclidean distance between the argument and the point the method is called on. Also override the stream insertion and extraction operators so that users can print the point to the screen in the format [x, y] and also input new values for a given point. Test your program with the points [4 2] and [-6 8]. Turn in copies of all three files needed to compile your program: main.cpp, XYPoint.cpp, and XYPoint.h.

Teacher's Comments: You were asked to override both the stream extraction (>>) and stream insertion (<<) operators. You have correctly overridden <<, but you did not override >>. And you need to do it in same program.

I dont know how to fix my program.


Here is my code:


//Header File

#ifndef XYPOINT_H
#define XYPOINT_H
#include <iostream>
using namespace std;
class XYPoint
{
public:
XYPoint();
XYPoint(float newx = 0,float newy= 0);


friend ostream& operator<<(ostream& stream, XYPoint& p );
float distance( XYPoint p,XYPoint q) ;
private:
float x;
float y;

};

#endif




//XYPoint.cpp File

#include <iostream>
using namespace std;
#include<cmath>
#include "XYPoint.h"

XYPoint::XYPoint()
{
x = 0;
y = 0;
}

XYPoint::XYPoint( float newx, float newy )
{
x = newx;
y = newy;
}

ostream& operator<<( ostream& stream, XYPoint& p)
{
stream << p.x << " " << p.y<<endl;
return stream;
}

float XYPoint::distance( XYPoint p,XYPoint q )
{
float distance = sqrt(pow((q.x-p.x),2)+pow((q.y-p.y),2));
return distance;
}



//main.cpp


#include "XYPoint.h"
#include<iostream>
#include <cmath>
using namespace std;

int main(void)
{
float x = 0;
float y = 0;

cout<<"Enter x value:";
cin>>x;
cout<<"Enter y value:";
cin>>y;

XYPoint point1(x,y);
XYPoint point2(-6, 8);

cout<<point1<<endl;
cout<<point2<<endl;

cout<<"Distance between these points is "<<point2.distance(point1,point2)<<endl;

return 1;
}
See:
http://www.cplusplus.com/reference/iostream/istream/operator%3E%3E/
http://www.cplusplus.com/reference/iostream/ostream/operator%3C%3C/

You have another subtle problem. You cannot define these two together:
1
2
XYPoint();
XYPoint(float newx = 0,float newy= 0);
The compiler cannot choose between the two if you write code like:
 
XYPoint x;
I recomend loosing the first constructor.
I believe the ambiguity problem that plague C++ is avoided entirely by Java. You just don't allow the programming language to accept default argument concept.
Topic archived. No new replies allowed.