用c++编写程序 【简答题】给出下面基类 class area public: protected: area(double h, double w) this->height = h; this->width = w; virtual double show_area0 = 0; double height; double width; 要求: (1)建立基类area的两个派生类rectangle与triangle,让两个派生类都包含一个函数show_area0,用来返回矩形与三 角形的面积。用构造函数对height与width进行初始化。 (2)写出主程序,用来求height与width分别为8.0与5.0的矩形面积,以及求height与width分别为3.0与7.0的三角 形面积。 (3)要求通过基类指针访问虚函数的方法(即运行时的多态性)分别求出矩形和三角形面积。
时间: 2024-03-23 17:36:31 浏览: 13
下面是代码实现:
```c++
#include <iostream>
using namespace std;
class area {
protected:
double height;
double width;
public:
area(double h, double w) {
this->height = h;
this->width = w;
}
virtual double show_area0() = 0;
};
class rectangle : public area {
public:
rectangle(double h, double w) : area(h, w) {}
double show_area0() {
return height * width;
}
};
class triangle : public area {
public:
triangle(double h, double w) : area(h, w) {}
double show_area0() {
return height * width / 2;
}
};
int main() {
area* p;
rectangle r(8.0, 5.0);
triangle t(3.0, 7.0);
p = &r;
cout << "rectangle area: " << p->show_area0() << endl;
p = &t;
cout << "triangle area: " << p->show_area0() << endl;
return 0;
}
```
输出结果为:
```
rectangle area: 40
triangle area: 10.5
```
其中,通过基类指针访问虚函数的方法,实现了运行时的多态性,分别求出了矩形和三角形的面积。