[英]Correctly implementing inheritance
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
. 因此每个几何体都有一个Rectangle
或Circle
类型的形状。 In my program I need to calculate the (Euclidean) distance between two geometries. 在我的程序中,我需要计算两个几何之间的(欧几里得)距离。 Thus, given two geometries g1
and g2
I call 因此,给定两个几何g1
和g2
我称之为
g1.distanceBetweenGeometries(g2);
and I want to return the distance between g1.myShape
and g2.myShape
. 我想返回g1.myShape
和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. 在Shape::distance(..)
我不知何故需要区分s1
和s2
是哪种类型。 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? 你能告诉我,我的继承理念是否足够,以及如何实现Shape::distance(..)
函数,以便它可以自动确定请求哪个公式进行距离计算?
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;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.