Given following classes:
class Geometry {
public:
double distanceBetweenGeometries(const Geometry& g);
private:
Shape myShape;
};
class Shape {
public:
double distance(const Shape& s1, const Shape& s2);
};
class Rectangle : public Shape {
private:
double i,j,length,width;
};
class Circle : public Shape {
private:
double i,j,radius;
};
So each geometry got a shape of type Rectangle or Circle. In my program I need to calculate the (Euclidean) distance between two geometries. Thus, given two geometries g1 and g2 I call
g1.distanceBetweenGeometries(g2);
and I want to return the distance between g1.myShape and g2.myShape.
I already know how to calculate the distance between two rectangles, two circles or between a rectangle and a circle. Somehow, I did not achieve an object-orientated solution for implementing the distance-function.
My idea is: Call the distance-function from a given geometry. This distance function calls the distance-function of a shape. In Shape::distance(..) I somehow need to differentiate of which type s1 and s2 are. Afterwards, I have to choose the correct mathematical formula to compute the distance between them. Can you tell me if my inheritance-idea is adequate here and how to implement the Shape::distance(..) function so that it can automatically determine which formula is requested for distance-computation?
You may do something like:
class Circle;
class Rectangle;
// Your existing methods to do the real computation:
double distanceRC(const Rectangle&, const Circle&);
double distanceRR(const Rectangle&, const Rectangle&);
double distanceCC(const Circle&, const Circle&);
class Shape {
public:
virtual ~Shape() = default;
virtual double distanceWith(const Shape&) const = 0;
virtual double distanceWith(const Rectangle&) const = 0;
virtual double distanceWith(const Circle&) const = 0;
};
class Rectangle : public Shape {
public:
double distanceWith(const Shape& s) const override { return s.distanceWith(*this); }
double distanceWith(const Rectangle& r) const override { return distanceRR(*this, r);}
double distanceWith(const Circle& c) const override { return distanceRC(*this, c); }
private:
double i,j,length,width;
};
class Circle : public Shape {
public:
double distanceWith(const Shape& s) const override { return s.distanceWith(*this); }
double distanceWith(const Rectangle& r) const override { return distanceRC(r, *this);}
double distanceWith(const Circle& c) const override { return distanceCC(*this, c); }
private:
double i,j,radius;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With