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 @ 2023-05-22 21:10  涨涨涨张  阅读(19)  评论(0编辑  收藏  举报