| const-members/situation-1/point.cc - The implementation of class Point - with compilation problems. | Lecture 4 - slide 26 : 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); // error: assignment of data-member Point::r in read-only structure
a = atan2(y,y); // error: assignment of data-member Point::a in read-only structure
is_polar_cached = true; // error: assignment of data-member Point::is_polar_cached in read-only structure
}
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() << ")" ;
}