const-members/situation-2/point.cc - The implementation of class Point - with compilation problems. | Lecture 4 - slide 27 : 40 Program 2 |
#include <cmath> #include <iostream> #include "point.h" Point::Point(double x_coord, double y_coord): x(x_coord), y(y_coord), is_polar_cached(false){ } Point::Point(): x(0.0), y(0.0), is_polar_cached(false){ } double Point::getx () const{ return x; } double Point::gety () const{ return y; } double Point::getr () const { if (is_polar_cached) return r; else{ do_polar_caching(); return r; } } double Point::geta () const { if (is_polar_cached) return a; else{ do_polar_caching(); return a; } } void Point::do_polar_caching() const{ // Must be const, when called from another const method. std::cout << "Caching" << std::endl; r = sqrt(x*x + y*y); // Now OK to update mutable data members a = atan2(y,y); is_polar_cached = true; } void Point::move(double dx, double dy){ is_polar_cached = false; x += dx; y += dy; } double Point::distance_to(Point p) const{ return sqrt((x - p.x) * (x - p.x) + (y - p.y) * (y - p.y)); } std::ostream& operator<<(std::ostream& s, const Point& p){ return s << "(" << p.getx() << "," << p.gety() << ")" ; }