声明一个基类Shape,只包含一个公有成员函数void

来源:百度知道 编辑:UC知道 时间:2024/07/05 07:06:39
声明一个基类Shape,只包含一个公有成员函数void Show(),在Show()中输出提示信息“This is a Shape!”;从Shape类公有派生出Rectangle类和Circle类,这2个类描述矩形和圆形,数据成员是私有的,定义公有的构造函数、公有的float GetArea()函数。在GetArea()中输出提示信息“This is a Shape of Rectangle(或Circle)!”,并且输出并返回具体形状的面积值。在主程序中生成Shape、 Rectangle、 Circle对象,分别通过3类对象调用Show(),通过Rectangle、 Circle对象调用GetArea()函数。

#include <iostream.h>
class Shape
{
public:
void Show(){cout<<"This is a Shape!\n";}
};

class Rectangle :public Shape
{
public:
Rectangle(float w,float h):width(w),height(h){}
float GetArea()
{
cout<<"This is a Shape of Rectangle!"<<endl;
return width*height;
}
private:
float width,height;
};

class Circle :public Shape
{
public:
Circle(float r):radius(r){}
float GetArea()
{
cout<<"This is a Shape of Circle!"<<endl;
return 3.14*radius*radius;
}
private:
float radius;
};

void main()
{
Shape s;
Rectangle r(100,50);
Circle c(100);
s.Show();
r.Show();
c.Show();
cout<<"The area of Rectangle is " << r.GetArea()<<endl;
cout<<"The area of Circle is