把定义平面直角坐标系上的一个点的类Point作为基类,派生出描述一条直线的类Line,在派生出一个矩形类Rect,要求成员函数能求出两点距离,矩形的周长和面积额等
时间: 2024-06-03 08:07:35 浏览: 200
设计基类点类(Point)、直接派生类圆类(Circle)、间接派生类圆柱体类(Cylinder),将求面积的函数(area)声明成虚函数,并在主函数实现虚函数
class Point {
protected:
double x, y;
public:
Point(double x = 0, double y = 0) : x(x), y(y) {}
double getX() const { return x; }
double getY() const { return y; }
void setX(double x) { this->x = x; }
void setY(double y) { this->y = y; }
};
class Line : public Point {
private:
double k, b;
public:
Line(double x1 = 0, double y1 = 0, double x2 = 0, double y2 = 0) : Point(x1, y1), k((y2 - y1) / (x2 - x1)), b(y1 - k * x1) {}
double getK() const { return k; }
double getB() const { return b; }
double getLength() const { return sqrt(pow(x - getX(), 2) + pow(y - getY(), 2)); }
};
class Rect : public Line {
private:
double width, height;
public:
Rect(double x1 = 0, double y1 = 0, double x2 = 0, double y2 = 0) : Line(x1, y1, x2, y2), width(getLength()), height(getLength()) {}
double getWidth() const { return width; }
double getHeight() const { return height; }
double getPerimeter() const { return 2 * (width + height); }
double getArea() const { return width * height; }
};
阅读全文