C++ Creating a function to get distance between two points -
in program have created constructor called point
2 values. have set
, get
, scale
, translate
function. i'm trying create function allows me distance between object , point. i'm have trouble though brilliant.
#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; = 1; cout << "\n default constructor called" << endl; } inline point::point(double anx, double ay) { cout << "\n regular constructor called"; } inline point::~point() { cout << "\n destructor called" << endl; } inline void point::setpoint(double anx, double ay) { thex = anx; = 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 translated : " << offsetx << endl; cout << "y translated : " << offsety << endl; } inline void point::distance(const point& apoint) { } #endif
cpp file:
#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 value x : " << mypoint.getx() << endl; cout << "\n value y : " << mypoint.gety() << endl; cout << "\n x scaled 2 : " << mypoint.scalex(2) << endl; cout << "\n y scaled 2 : " << mypoint.scaley(2) << endl; mypoint.translate(2, 3); cout << "\n main has finished" << endl; return 0; }
you need make point::getx()
, point::gety()
functions const
so:
inline double point::getx() const { return thex; }
if not const
cannot call them when parameter const
reference.
then distance (changed return 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); }
i have deliberately not used std::pow
since exponent 2. need include <cmath>
std::sqrt
.
Comments
Post a Comment