Advertisement
Guest User

Untitled

a guest
Apr 24th, 2013
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.54 KB | None | 0 0
  1.  
  2. #include <iostream>
  3. //#include <cmath>
  4. //#include <ctime>
  5.  
  6. using namespace std;
  7.  
  8. class Point
  9. {
  10. private:
  11.     double m_x;
  12.     double m_y;
  13.  
  14. public:
  15.  
  16.     // Default constructor
  17.     // Here we use initializer list ( after colon )
  18.     // instead of assignment in function body
  19.     Point() :
  20.         m_x(rand()*1.0 / RAND_MAX  * 100),
  21.         m_y(rand()*1.0 / RAND_MAX  * 100)
  22.     {
  23.  
  24.     }
  25.  
  26.     // And here too
  27.     // Note that, parameters passed by const reference,
  28.     // not by value
  29.     Point(const double& x, const double& y) :
  30.         m_x(x),
  31.         m_y(y)
  32.     {
  33.  
  34.     }
  35.  
  36.     // Accessors:
  37.     // "Getters" are constant functions, they must not change class members
  38.     double GetX() const { return m_x; }
  39.     double GetY() const { return m_y; }
  40.  
  41.     // "Setters", parameters passed by const reference
  42.     void SetX(const double& x) { m_x = x; }
  43.     void SetY(const double& y) { m_y = y; }
  44.  
  45.     double distanceTo(const Point& p)
  46.     {
  47.         // Deleted temp variables
  48.         // m_x and m_y changed to appropriate "getter"
  49.         return sqrt( pow( GetX() - p.GetX() , 2 ) + pow( GetY() - p.GetY() , 2) );
  50.     }
  51. };
  52.  
  53.  
  54. // Probably free function is more convenient here
  55. double Distance(const Point& a, const Point& b)
  56. {
  57.     return sqrt( pow( a.GetX() - b.GetX() , 2 ) + pow( a.GetY() - b.GetY() , 2) );
  58. }
  59.  
  60.  
  61.  
  62. void main()
  63. {
  64.     Point a(1.2, 0.5);
  65.     Point b;
  66.     b.SetX(2.71);
  67.     b.SetY(3.141592);
  68.    
  69.     cout << "Distance from (" << a.GetX() << ", " << a.GetY() << ") " ;
  70.     cout << "to (" << b.GetX() << ", " << b.GetY() << ") " ;
  71.     cout << "is " << Distance(a, b) << endl;
  72.    
  73.     system ("Pause");
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement