C ++创建一个函数来获得两点之间的距离

时间:2017-02-07 10:57:38

标签: c++ function object distance

在我的程序中,我创建了一个名为Point的构造函数,其中包含两个值。我还有setgetscaletranslate功能。我试图创建一个允许我获得对象和另一个点之间距离的函数。虽然任何帮助都很棒,但我遇到了麻烦。

#ifndef POINTMODEL
#define POINTMODEL
#define POINTDEB UG

#include <iostream>
#include <string.h>

using namespace std;

class Point {
public:
    Point(void);
    Point(double anX, double aY);
    ~Point();

    void setPoint(double anX, double aY);

    double getX();
    double getY();

    double scaleX(double theX);
    double scaleY(double theY);
    void translate(double theX, double theY);

    void distance(const Point& aPoint);

protected:
private:
    double theX;
    double theY;
};

inline Point::Point(void)
{
    theX = 1;
    theY = 1;
    cout << "\n The default constructor was called" << endl;
}

inline Point::Point(double anX, double aY)
{
    cout << "\n regular constructor called";
}

inline Point::~Point()
{
    cout << "\n the destructor was called" << endl;
}

inline void Point::setPoint(double anX, double aY)
{
    theX = anX;
    theY = aY;
}

inline double Point::getX()
{
    return theX;
}

inline double Point::getY()
{
    return theY;
}

inline double Point::scaleX(double theX)
{
    return theX;
}

inline double Point::scaleY(double theY)
{
    return theY;
}

inline void Point::translate(double offSetX, double offSetY)
{
    cout << "X is translated by : " << offSetX << endl;
    cout << "Y is translated by : " << offSetY << endl;
}

inline void Point::distance(const Point& aPoint)
{
}

#endif

Cpp文件:

#include "Point.h"

using namespace std;

int main(void)
{
    cout << "\n main has started" << endl;

    //Point myPoint;
    Point myPoint(1, 1);

    myPoint.setPoint(1, 1);

    cout << "\n The value for X is : " << myPoint.getX() << endl;
    cout << "\n The value for Y is : " << myPoint.getY() << endl;

    cout << "\n X scaled by 2 is : " << myPoint.scaleX(2) << endl;
    cout << "\n Y scaled by 2 is : " << myPoint.scaleY(2) << endl;

    myPoint.translate(2, 3);

    cout << "\n main has finished" << endl;

    return 0;
}

1 个答案:

答案 0 :(得分:3)

您需要按照以下方式设置Point::getX()Point::getY()个功能const

inline double Point::getX() const
{
    return theX;
}

如果它们不是const,则当参数为const引用时,您无法调用它们。

然后距离是(从void更改为double):

double distance(const Point & aPoint) const
{
    const double x_diff = getX() - aPoint.getX();
    const double y_diff = getY() - aPoint.getY();
    return std::sqrt(x_diff * x_diff + y_diff * y_diff);
}

我故意不使用std::pow,因为指数是2。 您还需要为<cmath>添加std::sqrt