Ghoztrider
Ghoztrider

Reputation: 145

Debugging Class Function Implementation C++

I could use some expertise in debugging my code if someone would kindly help. I'm trying to call a function from a class file and I'm running into a few errors. I'm in the process of learning c++. My errors are below:

In function 'int main()':    
error: no matching function for call to 'MyPoint::distance(MyPoint&)'
note: candidate is:
note: double MyPoint::distance(double)

Main.cpp

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

int main()
{
    MyPoint point1;
    MyPoint point2(10.2, 34.8);
    cout << point1.distance(point2);
    return 0;
}

MyPoint.h

#ifndef MYPOINT_H
#define MYPOINT_H
using namespace std;
class MyPoint
{
    public:
        MyPoint();
        MyPoint(double, double);
        double getX();
        double getY();
        double distance(double);
    private:
        double x, y;
};
#endif // MYPOINT_H

MyPoint.cpp

#include <iostream>
#include <cmath>
#include "MyPoint.h"
using namespace std;
MyPoint::MyPoint()
{
    x = 0.0;
    y = 0.0;
}

MyPoint::MyPoint(double x1, double y1)
{
    x = x1;
    y = y1;
}

double MyPoint::getX()
{
    return x;
}

double MyPoint::getY()
{
    return y;
}

double MyPoint::distance(double p2)
{
    return sqrt((x - p2.x) * (x - p2.x) + (y - p2.y) * (y - p2.y));
}

Thank you...

Upvotes: 0

Views: 820

Answers (3)

Anonymous
Anonymous

Reputation: 2172

You need to change distance method in your MyPoint class:

declare in .h

double distance(const MyPoint& p2);

implement in .cpp

double MyPoint::distance(const MyPoint& p2)
{
    return sqrt((x - p2.x) * (x - p2.x) + (y - p2.y) * (y - p2.y));
}

Upvotes: 0

Eugene Sh.
Eugene Sh.

Reputation: 18351

Your double MyPoint::distance(double p2) is a wrong definition. It should receive MyPoint instead of double

Upvotes: 0

Nick Veys
Nick Veys

Reputation: 23939

You declared distance as this:

double distance(double);

Which means the MyPoint::distance method expects a double, not another MyPoint. It looks like you can just change the delcaration and it might work.

In your header:

double distance(MyPoint&);

and your implementation:

double MyPoint::distance(MyPoint& p2)

Upvotes: 1

Related Questions