I can’t figure out why this program won’t work. I’m sure it’s something basic.
#include <iostream>
using namespace std;
class MyPoint
{
int x;
int y;
public:
MyPoint()
{
x = 0;
y = 0;
}
MyPoint(int newX, int newY)
{
x = newX;
y = newY;
}
int getX()
{
return x;
}
int getY()
{
return y;
}
int distance(MyPoint newPoint)
{
distance = x - newPoint.getX();//need absolute value function
return distance;
};
int main()
{
MyPoint point1(0,0);
MyPoint point2(5,5);
cout << "THe distance between the two circles is " << point1.distance(point2) << endl;
return 0;
}
I’m trying to find the distance between two points and just to test to make sure that I am using classes correctly. I am just using the x point only. Right now the code will not compile.
Your problem lies in the
distancefunction:Here, you have a variable named
distance, which is not declared anywhere, and also is overloaded with the function name. Instead, you need to declare a new local variable and then return it, or just return it right away:Option 1:
Option 2: