编写程序声明一个Shape基类,再派生出Rectangle和Circle类,二者都有GetArea()函数计算对象的面积

如题所述

楼上用的是java,既然说到基类和派生类,我想应该是指用C++实现,以下是我的方法:
#include <iostream.h>
class Shape{
//这里可以自己添加数据成员或成员函数
};
class Rectangle:public Shape
{
double height,width;
public:
Rectangle(double h=1.0,double w=1.0)//该构造函数用于初始化矩形类的数据成员
{
height=h;
width=w;
}
double GetArea()//计算矩形面积
{
return height*width;
}
};
class Circle:public Shape
{
double radius;
public:
Circle(double r=1.0)//该构造函数用于初始化圆形类的数据成员
{
radius=r;
}

double GetArea()//计算圆形面积
{
return 3.14*radius*radius;
}
};
void main()
{
Rectangle a(10.5,11.5);
cout<<a.GetArea()<<endl;
Circle b(2.5);
cout<<b.GetArea()<<endl;
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-06-25
interface Shape{
float GetArea();}/*建立接口*/
class Rectangle inplements Shape
{ float GetArea()
{return 面积算法;}
class Circle inplements Shape
{ float GetArea()
{return 面积算法;}
第2个回答  2013-06-25
你想用什么语言来编的,又没说明?
相似回答