簡體   English   中英

C ++創建一個函數以獲取兩點之間的距離

[英]C++ Creating a function to get distance between two points

在我的程序中,我創建了一個帶有兩個值的名為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;
}

您需要使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。您還需要為std::sqrt包括<cmath>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM