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;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统