虚函数计算面积

#include <iostream>
#include <iomanip>
using namespace std;
class Shape{
public:
const double PI;
Shape():PI(3.1415926){
}
virtual double Area()=0;
};
class Circle:public Shape{
private:
double rad;
public:
double Area(){
setRad();
return PI * rad * rad;
}
void setRad(){
cin>>rad;
}
};
class Square:public Shape{
private:
double side;
public:
void setSide(){
cin>>side;
}
double Area(){
setSide();
return side * side;
}
};
class Rectangle:public Shape{
private:
double len,w;
public:
void setRec(){
cin>>len>>w;
}
double Area(){
setRec();
return len * w;
}
};
class Trapezoid:public Shape{
private:
double s,x,high;
public:
void setTra(){
cin>>s>>x>>high;
x = s;
}
double Area(){
setTra();
return (s + x) * high / 2;
}
};
class Triangle:public Shape{
private:
double d,h;
public:
void setTri(){
cin>>d>>h;
}
double Area(){
setTri();
return d * h / 2;
}
};
int main()
{
Shape *p[5];
double total = 0;
p[0] = new Circle;
p[1] = new Square;
p[2] = new Rectangle;
p[3] = new Trapezoid;
p[4] = new Triangle;
cout<<fixed<<setprecision(3);
for(int i = 0; i < 5; i++)
{
total += p[i]->Area();
delete p[i];
}
cout<<" "<<total<<endl;
return 0;
}

posted @ 2023-05-23 08:51  不会JAVA的小袁  阅读(15)  评论(0编辑  收藏  举报