声明一个基类Shape,在此基础上派生出Rectangle和Circle,二者都有GetArea()函数计算对象的面积.

使用Rectangle类创建一个派生类Square.
2024-12-26 18:32:11
推荐回答(1个)
回答1:

class Shape
{
public:
virtual double GetArea()=0;
};

class Rectangle : public Shape
{
public:
Rectangle(double h, double w) : height(h), width(w){}
double GetArea(){ return height * width; }
private:
double height;
double width;
};
class Circle : public Shape
{
public:
Circle(double r):radius(r){}
double GetArea(){ return 3.14159 * radius * radius; }
private:
double radius;
};

class Square : public Rectangle
{
public:
Square(double l) : Rectangle(l, l){}
};