【问题描述】 定义一个图形类(figure),其中有保护类型的成员数据:高度(height)和宽度(width),一个公有的构造函数。由该图形类建立两个派生类:矩形类(rectangle)和等腰三角形类(triangle)。在每个派生类中都包含一个函数area(),分别用来计算矩形和等腰三角形的面积. 还有display()函数,显示对象的信息. 主函数如下: int main() { double width,height; cin>>width>>height; triangle tri(width,height); rectangle rect(width,height); tri.display(); cout<<"The area is "<<tri.area()<<endl; rect.display(); cout<<"The area is "<<rect.area()<<endl; return 0; } 【输入形式】宽度和高度 【输出形式】主函数输出,注意标点、空格 按主函数输出 【样例输入】3 4 【样例输出】 I am a triangle. The value of width is 3, the height is 4.The area is 6 I am a rectangle. The value of width is 3, the height is 4.The area is 12
时间: 2023-12-28 21:04:43 浏览: 17
```cpp
#include <iostream>
using namespace std;
class Figure {
protected:
double height;
double width;
public:
Figure(double h, double w) : height(h), width(w) {}
virtual double area() = 0; // 纯虚函数
virtual void display() = 0; // 纯虚函数
};
class Rectangle : public Figure {
public:
Rectangle(double h, double w) : Figure(h, w) {}
double area() override {
return height * width;
}
void display() override {
cout << "I am a rectangle. The value of width is " << width << ", the height is " << height << ".";
}
};
class Triangle : public Figure {
public:
Triangle(double h, double w) : Figure(h, w) {}
double area() override {
return height * width / 2;
}
void display() override {
cout << "I am a triangle. The value of width is " << width << ", the height is " << height << ".";
}
};
int main() {
double width, height;
cin >> width >> height;
Triangle tri(width, height);
Rectangle rect(width, height);
tri.display();
cout << " The area is " << tri.area() << endl;
rect.display();
cout << " The area is " << rect.area() << endl;
return 0;
}
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)