Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- //#include <cmath>
- //#include <ctime>
- using namespace std;
- class Point
- {
- private:
- double m_x;
- double m_y;
- public:
- // Default constructor
- // Here we use initializer list ( after colon )
- // instead of assignment in function body
- Point() :
- m_x(rand()*1.0 / RAND_MAX * 100),
- m_y(rand()*1.0 / RAND_MAX * 100)
- {
- }
- // And here too
- // Note that, parameters passed by const reference,
- // not by value
- Point(const double& x, const double& y) :
- m_x(x),
- m_y(y)
- {
- }
- // Accessors:
- // "Getters" are constant functions, they must not change class members
- double GetX() const { return m_x; }
- double GetY() const { return m_y; }
- // "Setters", parameters passed by const reference
- void SetX(const double& x) { m_x = x; }
- void SetY(const double& y) { m_y = y; }
- double distanceTo(const Point& p)
- {
- // Deleted temp variables
- // m_x and m_y changed to appropriate "getter"
- return sqrt( pow( GetX() - p.GetX() , 2 ) + pow( GetY() - p.GetY() , 2) );
- }
- };
- // Probably free function is more convenient here
- double Distance(const Point& a, const Point& b)
- {
- return sqrt( pow( a.GetX() - b.GetX() , 2 ) + pow( a.GetY() - b.GetY() , 2) );
- }
- void main()
- {
- Point a(1.2, 0.5);
- Point b;
- b.SetX(2.71);
- b.SetY(3.141592);
- cout << "Distance from (" << a.GetX() << ", " << a.GetY() << ") " ;
- cout << "to (" << b.GetX() << ", " << b.GetY() << ") " ;
- cout << "is " << Distance(a, b) << endl;
- system ("Pause");
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement