【C++继承】图形类 【问题描述】 定义一个图形类(figure),其中有保护类型的成员数据:高度(height)和宽度(width),一个公有的构造函数。由该图形类建立两个派生类:矩形类(rectangle)和等腰三角形类(triangle)。在每个派生类中都包含一个函数area(),分别用来计算矩形和等腰三角形的面积. 还有display()函数,显示对象的信息.
时间: 2024-01-21 17:18:27 浏览: 116
以下是C++的代码实现:
```cpp
#include<iostream>
using namespace std;
class figure{
protected:
int height;
int width;
public:
figure(int h,int w){
height=h;
width=w;
}
};
class rectangle:public figure{
public:
rectangle(int h,int w):figure(h,w){}
int area(){
return height*width;
}
void display(){
cout<<"This is a rectangle with height "<<height<<" and width "<<width<<endl;
}
};
class triangle:public figure{
public:
triangle(int h,int w):figure(h,w){}
int area(){
return height*width/2;
}
void display(){
cout<<"This is a triangle with height "<<height<<" and width "<<width<<endl;
}
};
int main(){
rectangle rec(3,4);
cout<<"The area of the rectangle is "<<rec.area()<<endl;
rec.display();
triangle tri(3,4);
cout<<"The area of the triangle is "<<tri.area()<<endl;
tri.display();
return 0;
}
```
运行结果:
```
The area of the rectangle is 12
This is a rectangle with height 3 and width 4
The area of the triangle is 6
This is a triangle with height 3 and width 4
```
阅读全文