用c++写一个程序,要求:定义一个图形类Figure,其中有保护的成员数据:高度(height)和宽度(width),一个公有的构造函数和一个纯虚函数getArea()。由该图形类建立两个派生类:矩形类Rectangle和等腰三角形类Triangle(其中宽度为等腰三角形底边长,高度为等腰三角形的高度)。在每个派生类中都实现了getArea()函数,分别用来计算矩形和等腰三角形的面积。
时间: 2024-03-01 14:52:49 浏览: 16
以下是一个符合要求的C++程序:
```cpp
#include <iostream>
using namespace std;
class Figure {
protected:
int height;
int width;
public:
Figure(int h, int w): height(h), width(w) {}
virtual double getArea() const = 0; // 纯虚函数
};
class Rectangle : public Figure {
public:
Rectangle(int h, int w): Figure(h, w) {}
virtual double getArea() const {
return height * width;
}
};
class Triangle : public Figure {
public:
Triangle(int h, int w): Figure(h, w) {}
virtual double getArea() const {
return height * width / 2.0;
}
};
int main() {
Figure* fig1 = new Rectangle(5, 10);
Figure* fig2 = new Triangle(5, 10);
cout << "矩形面积为:" << fig1->getArea() << endl; // 输出50
cout << "三角形面积为:" << fig2->getArea() << endl; // 输出25
delete fig1;
delete fig2;
return 0;
}
```
程序中首先定义了一个图形类`Figure`,包含两个保护成员属性:`height`表示高度,`width`表示宽度。构造函数用于初始化这两个属性。`getArea()`函数是一个纯虚函数,没有实现,用于计算图形面积。由于`getArea()`是纯虚函数,所以`Figure`类是一个抽象类,不能直接实例化对象。
接下来,我们定义了两个派生类:矩形类`Rectangle`和等腰三角形类`Triangle`。在这两个类中,我们重载了`getArea()`函数,分别用于计算矩形和等腰三角形的面积。由于这两个类继承自`Figure`类,所以它们都可以使用`height`和`width`属性。
在主函数中,我们使用`new`运算符创建了一个矩形对象`fig1`和一个等腰三角形对象`fig2`,并分别调用它们的`getArea()`函数计算面积并输出。最后,我们使用`delete`运算符释放了它们的内存空间。