多态性(图形的面积)

                多态性2(图形的面积)
      定义一个形状类shape,将它作为基类派生出类:circle(圆)、triangle(三角形)和rectangle(长方形)。

分别定义这些派生类并且定一个虚函数来计算各个形状的面积。
#include
#include<math.h>
#include
using namespace std;
///基类Shape
class Shape
{
public:
void virtual printArea() = 0;//纯虚函数
};

//派生类Circle
class Circle : public Shape
{
public:
Circle(double r = 0):radius®{}//构造函数
void printArea(){cout<<fixed<<setprecision(3)<<3.14 * radius * radius<<endl;}
private:
double radius;//数据成员,表示半径
};

//派生类Rectangle
class Rectangle : public Shape
{
public:
Rectangle(double w,double h):width(w),height(h){}//构造函数
void printArea(){cout<<fixed<<setprecision(3)<<width * height<<endl;}
private:
double width;//数据成员,表示宽
double height;//数据成员,表示长
};

//派生类Triangle
class Triangle : public Shape
{
public:
Triangle(double w,double h,double u):width(w),height(h),gun(u){} //构造函数
void printArea(){
double f;
f=(width+height+gun)/2;
cout<<fixed<<setprecision(3)<<sqrt(f*(f-width)(f-height)(f-gun))<<endl;}
private:
double width;//数据成员,表示底
double height;//数据成员,表示高
double gun;
};

//主函数
int main()
{
Shape *s;
double a,b,c,d,e,f;
while(cin>>a>>b>>c>>d>>e>>f){
Circle circle(a);
Rectangle rectangle(e,f);
Triangle triangle(b,c,d);
s = &circle;
s->printArea();
s = ▵
s->printArea();
s = &rectangle;
s->printArea();
}
return 0;
}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值