# C++习题 抽象基类

C++习题 抽象基类

``````12.6
4.5 8.4
4.5 8.4
``````

``````area of circle = 498.76
area of rectangle = 37.80
area of triangle = 18.90
``````

``````#include<stdio.h>
int main()
{
float a,b,c,d,e;
scanf("%f",&a);
scanf("%f %f",&b,&c);
scanf("%f %f",&d,&e);
printf("area of circle = %.2f\n",a*3.1415926535898*a);
printf("area of rectangle = %.2f\n",b*c);
printf("area of triangle = %.2f\n",d*e/2);
}``````

``````#include<iostream>
#include<iomanip>
using namespace std;
class Shape
{
public:
virtual double Area()=0;
};
class Circle:public Shape
{
public:
Circle(double R):r(R){}
virtual double Area()
{
return 3.1415926*r*r;
}
private:
double r;
};
class Rectangle:public Shape
{
public:
Rectangle(double a,double b):chang(a),kuan(b){};
virtual double Area()
{
return chang*kuan;
}
private:
double chang,kuan;
};
class Triangle:public Shape
{
public:
Triangle(double a,double b):di(a),gao(b){};
virtual double Area()
{
return di*gao/2;
}
private:
double di,gao;
};

void printArea(Shape& shape)
{
cout<<shape.Area()<<endl;
}
int main()
{
float r,a,b,w,h;
cout<<fixed<<setprecision(2);
cin>>r;
Circle circle(r);
cout<<"area of circle = ";
printArea(circle);
cin>>a>>b;
Rectangle rectangle(a,b);
cout<<"area of rectangle = ";
printArea(rectangle);
cin>>w>>h;
Triangle triangle(w,h);
cout<<"area of triangle = ";
printArea(triangle);
return 0;
}
``````