三个选择题

在这里插入图片描述

Shape类的继承

【问题描述】定义一个Shape基类,在此基础上派生出Rectangle和Circle类,二者都有GetArea()函数计算对象的面积,使用Rectangle类创建一个派生类Square。并应用相应类的对象测试。【注意:π取3.14】

【输入形式】三种形状基本数据。

【输出形式】对应每种形状的面积。
在这里插入图片描述
【样例说明】第一行的数据为基本数据(四个),分别为圆形半径,长方形长和宽,正方形边长。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include<iostream>
using namespace std;
class Shape {
public:
Shape(){}
~Shape(){}
virtual float GetArea() {return -1;}
};
class Circle :public Shape
{
private:
float r;
public:
Circle(float rr):r(rr){}
virtual float GetArea()
{
return (3.14*r*r);
}
};
class Rectangle:public Shape
{
protected:
float l,h;
public:
Rectangle(float ll,float hh):l(ll),h(hh){}
virtual float GetArea()
{
return (l*h);
}
};
class Square: public Rectangle
{
public:
Square(float ss):Rectangle(ss,ss){}
virtual float GetArea()
{
return (h*l);
}
};
int main()
{
Shape *sp;
int radium,length,hight,side;
cin>>radium>>length>>hight>>side;
sp=new Circle(radium);
cout<<"The area of the circle is "<<sp->GetArea()<<endl;
sp=new Rectangle(length,hight);
cout<<"The area of the rectangle is "<<sp->GetArea()<<endl;
sp=new Square(side);
cout<<"The area of the Square is "<<sp->GetArea()<<endl;
delete sp;
return 0;
}

 评论

载入天数...载入时分秒...