C++

虚函数,抽象类

声明抽象基类Shape,由它派生出三个类,圆形Circle,矩形Rectangle,三角形Triangle,用一个函数输出三个面积。

#include <iostream>
#include <iomanip>
using namespace std;

class Shape
{
public:
Shape()
{}
Shape(double s[])
{}
virtual double Area()=0;

};
class Circle:public Shape
{
public:
Circle(double r)
{
this->r=r;
}
double Area()
{
return r*r*3.1415926;
}
private:
double r;
};

class Rectangle:public Shape
{
public:
Rectangle(double x,double y)
{
this->x=x;
this->y=y;
}
double Area()
{
return x*y;
}
private:
double x;
double y;
};

class Triangle:public Shape
{
public:
Triangle(double h,double d)
{
this->h=h;
this->d=d;
}
double Area()
{
return h*d/2;
}
private:
double h;
double d;
};

int main()
{
Shape* shape[3];
double r,x,y,h,d;
cin>>r>>x>>y>>h>>d;
shape[0]=new Circle(r);
shape[1]=new Rectangle(x,y);
shape[2]=new Triangle(h,d);
cout<<fixed<<showpoint<<setprecision(2)<<shape[0]->Area()<<endl;
cout<<fixed<<showpoint<<setprecision(2)<<shape[1]->Area()<<endl;
cout<<fixed<<showpoint<<setprecision(2)<<shape[2]->Area()<<endl;
return 0;
}

posted @   涨涨涨张  阅读(23)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
点击右上角即可分享
微信分享提示