定义抽象类 Shape 及其子类Circle 和 Rectangle,要求: (1)抽象类Shape 具有纯虛函数 Area(),用于计算其子类的面积; (2)抽象类Shape的子类 Circle、Rectangle,覆盖父类的Area()方法,用于计算各自的面积; (3)通过Shape 类指针分別指向 Circle对象、Rectagnle 对象,并调用Aera()方法用于输出面积。
时间: 2024-03-22 08:41:37 浏览: 25
下面是实现上述要求的示例代码:
```cpp
#include <iostream>
using namespace std;
// 抽象类 Shape
class Shape {
public:
// 纯虚函数,用于计算面积
virtual double Area() = 0;
};
// Circle 类,继承自 Shape
class Circle : public Shape {
public:
Circle(double r) : radius(r) {}
// 重写父类 Area() 方法,计算圆的面积
double Area() {
return 3.14159 * radius * radius;
}
private:
double radius;
};
// Rectangle 类,继承自 Shape
class Rectangle : public Shape {
public:
Rectangle(double w, double h) : width(w), height(h) {}
// 重写父类 Area() 方法,计算矩形的面积
double Area() {
return width * height;
}
private:
double width;
double height;
};
int main() {
// 通过 Shape 类指针分别指向 Circle 对象、Rectangle 对象
Shape *shape1 = new Circle(2.0);
Shape *shape2 = new Rectangle(3.0, 4.0);
// 调用各自的 Area() 方法计算面积并输出
cout << "Circle area: " << shape1->Area() << endl;
cout << "Rectangle area: " << shape2->Area() << endl;
delete shape1;
delete shape2;
return 0;
}
```
在上述代码中,Shape类是一个抽象类,其中定义了纯虚函数Area(),用于计算其子类的面积。Circle类和Rectangle类是Shape类的子类,分别覆盖了父类的Area()方法,用于计算各自的面积。在main()函数中,通过Shape类指针指向Circle对象和Rectangle对象,并分别调用了各自的Area()方法,用于计算和输出面积。