编写一个c++程序,给出下面的基类,要求: (1)建立基类Area的俩个派生类Rectangle(矩形)与Isosceles(三角形),让每一个派生类都包含一个函数getArea(),分别用来返回矩形与三角形的面积。用构造函数对height与wi
时间: 2024-03-23 12:42:24 浏览: 25
dth进行初始化。(2)在主函数中创建一个Rectangle对象和一个Isosceles对象,调用它们的getArea()函数分别输出它们的面积。
以下是程序代码:
```c++
#include <iostream>
using namespace std;
class Area {
protected:
int height;
int width;
public:
Area(int h, int w) {
height = h;
width = w;
}
virtual int getArea() = 0;
};
class Rectangle : public Area {
public:
Rectangle(int h, int w) : Area(h, w) {}
int getArea() {
return height * width;
}
};
class Isosceles : public Area {
public:
Isosceles(int h, int w) : Area(h, w) {}
int getArea() {
return height * width / 2;
}
};
int main() {
Rectangle r(5, 10);
Isosceles i(5, 10);
cout << "Rectangle Area: " << r.getArea() << endl;
cout << "Isosceles Area: " << i.getArea() << endl;
return 0;
}
```
解释一下代码:
首先定义了一个基类 Area,其中包含了两个 protected 的成员变量 height 和 width,以及一个纯虚函数 getArea(),用来计算面积。在派生类 Rectangle 和 Isosceles 中,分别实现了 getArea() 函数,并在构造函数中对 height 和 width 进行了初始化。在主函数中,分别创建了一个 Rectangle 对象和一个 Isosceles 对象,并调用它们的 getArea() 函数输出面积。注意,这里用到了虚函数,保证了程序的多态性。